Maximum Height of Every Island
Learn this problemProblem statement
Given a rectangular integer matrix grid, return the maximum height of every island.
For this exercise, assume 0 represents background and every positive value represents land with that height. Two land cells belong to the same island when they share an edge; diagonal contact alone does not connect them.
Return one maximum per island in row-major discovery order: scan cells from top to bottom and left to right, and emit an island's maximum when its first cell is encountered.
Function
islandMaximumHeights(grid: int[][]) → int[]Examples
Example 1
grid = [[1,2,0,4],[0,3,0,5],[6,0,7,0],[6,0,7,8]]return = [3,5,6,8]The row-major scan first reaches islands with maximum heights 3, 5, 6, and 8, in that order.
Example 2
grid = [[5,0],[0,9]]return = [5,9]The two positive cells touch only diagonally, so they form separate islands whose maxima are 5 and 9.
Example 3
grid = [[2,1],[4,3]]return = [4]Every cell is connected through shared edges, so there is one island and its maximum height is 4.
Constraints
gridhas at least one row and one column and is rectangular.- Every cell is a nonnegative 32-bit integer.
0is background; every positive value is land.- Island connectivity is horizontal and vertical only.