Advertisement
892. Surface Area of 3D Shapes
MediumView on LeetCode
Time: O(n²)
Space: O(1)
Approach
Per cell contribute 4·h+2 faces; subtract 2·min(h, neighbor) for each shared wall with adjacent cells.
892.cs
C#
// Approach: Per cell contribute 4·h+2 faces; subtract 2·min(h, neighbor) for each shared wall with adjacent cells.
// Time: O(n²) Space: O(1)
public class Solution
{
public int SurfaceArea(int[][] grid)
{
int ans = 0;
int n = grid.Length;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (grid[i][j] > 0)
ans += grid[i][j] * 4 + 2;
if (i > 0)
ans -= Math.Min(grid[i][j], grid[i - 1][j]) * 2;
if (j > 0)
ans -= Math.Min(grid[i][j], grid[i][j - 1]) * 2;
}
}
return ans;
}
}Advertisement
Was this solution helpful?