1122. Ring Totals
A gardener plants flowers in an m x n bed and wants to know how much each concentric border holds. The bed is given as the integer grid grid. Ring r is the set of cells whose distance to the nearest edge, min(row, col, m-1-row, n-1-col), equals r, so ring 0 is the outer frame.
Return an array holding the sum of every ring, outermost ring first. The array has ceil(min(m, n) / 2) entries. For example a 1 x n bed has a single ring that contains every cell.
Constraints: 1 <= m, n <= 50 and -1000 <= grid[i][j] <= 1000. A single pass over the cells that adds each value to its ring runs in O(m*n) time with O(min(m, n)) extra space.
Example 1
- Input:
- grid = [[1,2,3],[4,5,6],[7,8,9]]
- Output:
- [40,5]
- Explanation:
The outer ring holds 1+2+3+6+9+8+7+4 = 40 and the centre ring is just 5.
Example 2
- Input:
- grid = [[1,1,1,1],[1,5,6,1],[1,7,8,1],[1,1,1,1]]
- Output:
- [12,26]
- Explanation:
The border has twelve ones and the inner 2 x 2 block sums to 26.
Example 3
- Input:
- grid = [[3,-2,4,1,0],[5,6,7,8,9]]
- Output:
- [41]
- Explanation:
A 2 x 5 grid has a single ring, so all ten values are added: 41.
Constraints
1 ≤ m, n ≤ 50
-1000 ≤ grid[i][j] ≤ 1000
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Expected complexity
- Time
- O(m*n)
- Space
- O(min(m, n))