Minimum Operations to Make Columns Strictly Increasing Problem
Description
LeetCode Problem 3402.
You are given a m x n matrix grid consisting of non-negative integers.
In one operation, you can increment the value of any grid[i][j] by 1.
Return the minimum number of operations needed to make all columns of grid strictly increasing.
Example 1:
Input: grid = [[3,2],[1,3],[3,4],[0,1]]
Output: 15
Explanation:
- To make the 0^th column strictly increasing, we can apply 3 operations on grid[1][0], 2 operations on grid[2][0], and 6 operations on grid[3][0].
- To make the 1^st column strictly increasing, we can apply 4 operations on grid[3][1].

Example 2:
Input: grid = [[3,2,1],[2,1,0],[1,2,3]]
Output: 12
Explanation:
- To make the 0^th column strictly increasing, we can apply 2 operations on grid[1][0], and 4 operations on grid[2][0].
- To make the 1^st column strictly increasing, we can apply 2 operations on grid[1][1], and 2 operations on grid[2][1].
- To make the 2^nd column strictly increasing, we can apply 2 operations on grid[1][2].

Constraints:
m == grid.lengthn == grid[i].length1 <= m, n <= 500 <= grid[i][j] < 2500
Solution
Approach: Column by Column
Columns are independent, so handle each one on its own, top to bottom. Keep pre, the value the previous cell ended up with (start at -1).
For the current cell cur: if pre < cur, nothing is needed and pre becomes cur. Otherwise the cell must be raised to pre + 1, which is the smallest value that keeps the column strictly increasing. That costs pre + 1 - cur operations, and pre becomes pre + 1.
Raising as little as possible keeps later cells cheap, so the sum over all columns is the minimum.
Complexity: O(mn) time, O(1) extra space.
class Solution:
def minimumOperations(self, grid: List[List[int]]) -> int:
ans = 0
for col in zip(*grid):
pre = -1
for cur in col:
if pre < cur:
pre = cur
else:
pre += 1
ans += pre - cur
return ans