A logistics yard is laid out as an n x n grid of storage cells. Each cell (i, j) holds a vertical stack of unit-cube crates, v[i][j] crates tall (a stack may be empty). Before shipping, the yard crew shrink-wraps every exposed face of every crate: the top of the tallest crate in a stack, the bottom of the lowest crate (crates sit directly on the yard floor, and that bottom face still needs wrap), and every side face that is not pressed against another crate of at least the same height in an adjacent stack (front, back, left, right). Two side-by-side stacks that touch shield each other's facing walls up to whichever stack is shorter; the part of the taller stack that rises above that shared height is still exposed and needs wrap on that side. Given the grid of stack heights, find the total area, in unit squares, of shrink-wrap material required to cover every exposed face of every crate in the yard.
Example 1
Input
1 2
Expected
10
Explanation
A single stack of height 2 has no neighbors, so it contributes its full isolated surface: 2 (top + bottom) plus 4 * 2 = 8 for the four side walls, for a total of 10.
Example 2
Input
2 1 2 3 4
Expected
34
Explanation
Treated in isolation the four stacks contribute (2+4*1)+(2+4*2)+(2+4*3)+(2+4*4) = 6+10+14+18 = 48. Adjacent stacks then shield each other along their shared wall: the top-left/top-right pair (heights 1 and 2) hides 2*min(1,2)=2, the top-left/bottom-left pair (heights 1 and 3) hides 2*min(1,3)=2, the top-right/bottom-right pair (heights 2 and 4) hides 2*min(2,4)=4, and the bottom-left/bottom-right pair (heights 3 and 4) hides 2*min(3,4)=6, removing 2+2+4+6=14 in total. 48 - 14 = 34.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →