
Sponsored
Sponsored
In this approach, we calculate each plane's projection separately, then sum them up for the total projection area. For the XY-plane projection, we count every cell with a positive value. For the YZ-plane, we determine the maximum value in each row (representing the view from the side). For the ZX-plane, we find the maximum value in each column (representing the view from the front).
Time Complexity: O(n^2) since we traverse each grid element once.
Space Complexity: O(1) since we use no additional space proportional to the input size.
1class Solution {
2 public int projectionArea(int[][] grid) {
3 int xy = 0, yz = 0, zx = 0;
4 for (int i = 0; i < grid.length; i++) {
5 int yz_max = 0, zx_max = 0;
6 for (int j = 0; j < grid[i].length; j++) {
7 if (grid[i][j] > 0) xy++;
8 yz_max = Math.max(yz_max, grid[i][j]);
9 zx_max = Math.max(zx_max, grid[j][i]);
10 }
11 yz += yz_max;
12 zx += zx_max;
13 }
14 return xy + yz + zx;
15 }
16 public static void main(String[] args) {
17 Solution sol = new Solution();
18 int[][] grid = {{1,2},{3,4}};
19 int result = sol.projectionArea(grid);
20 }
21}Java solution iterating over grid rows and columns, computing maximum values for YZ and ZX projections for a side and front view respectively.
This approach improves upon the earlier method by precomputing the maximum values in each row and column before calculating the projections. By storing these values in separate arrays, it helps avoid repeatedly calculating max values within nested loops for each axis projection.
Time Complexity: O(n^2) to fill the grid, row, and column arrays.
Space Complexity: O(n) to store column maximums.
1
JavaScript implementation precomputes maximum values for each row and column before deriving the projections to enhance runtime by mitigating repetitive calculations for these during iteration.