A community garden is laid out as a grid of m rows by n columns of planter cells, with row 0 at the top and row m-1 at the bottom; cell (r, c) currently holds a soil mound of height grid[r][c]. For structural reasons, every column must end up with soil heights that strictly increase as you move down from the top cell to the bottom cell: grid[r][c] must be less than grid[r+1][c] for every row r from 0 to m-2, in every column c. The only action available is adding one unit of soil to a single cell, which increases that cell's height by exactly 1 and counts as one operation; soil can never be removed. Determine the minimum total number of soil-adding operations needed so that every column's heights strictly increase from top to bottom.
Print a single integer: the minimum total number of soil-adding operations required.
Example 1
Input
2 2 1 5 1 5
Expected
2
Explanation
Column 0 holds heights [1, 1] top to bottom; the bottom cell must exceed 1, so it needs one unit of soil to become 2. Column 1 holds [5, 5]; likewise its bottom cell needs one unit to become 6. Total: 1 + 1 = 2 operations.
Example 2
Input
3 2 3 1 3 1 3 1
Expected
6
Explanation
Column 0 holds [3, 3, 3] top to bottom: the second cell must exceed 3 so it rises to 4 (1 unit), and the third cell must then exceed 4 so it rises to 5 (2 units) -- 3 units total. Column 1 holds [1, 1, 1] and needs the same pattern, 1 + 2 = 3 units. Total: 3 + 3 = 6 operations.
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 →