Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

883. Projection Area of 3D Shapes

Explanation:

To calculate the total area of all three projections, we need to consider the areas projected onto the xy, yz, and zx planes separately.

Steps:

  1. For the xy-plane projection, the area is the sum of the maximum height of each column in the grid.
  2. For the yz-plane projection, the area is the sum of the maximum height of each row in the grid.
  3. For the zx-plane projection, the area is the sum of all non-zero values in the grid.

Time Complexity:

The time complexity of this algorithm is O(n^2) where n is the size of the grid.

Space Complexity:

The space complexity is O(1) as we are not using any extra space.

:

class Solution {
    public int projectionArea(int[][] grid) {
        int xy = 0, yz = 0, zx = 0;
        
        for (int i = 0; i < grid.length; i++) {
            int maxRow = 0, maxCol = 0;
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] > 0) zx++;
                maxRow = Math.max(maxRow, grid[i][j]);
                maxCol = Math.max(maxCol, grid[j][i]);
            }
            xy += maxRow;
            yz += maxCol;
        }
        
        return xy + yz + zx;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.