Skip to content

3402. Minimum Operations to Make Columns Strictly Increasing 👍

  • Time: $O(mn)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  int minimumOperations(vector<vector<int>>& grid) {
    int ans = 0;

    for (int j = 0; j < grid[0].size(); ++j)
      for (int i = 1; i < grid.size(); ++i)
        if (grid[i][j] <= grid[i - 1][j]) {
          ans += grid[i - 1][j] - grid[i][j] + 1;
          grid[i][j] = grid[i - 1][j] + 1;
        }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int minimumOperations(int[][] grid) {
    int ans = 0;

    for (int j = 0; j < grid[0].length; ++j)
      for (int i = 1; i < grid.length; ++i)
        if (grid[i][j] <= grid[i - 1][j]) {
          ans += grid[i - 1][j] - grid[i][j] + 1;
          grid[i][j] = grid[i - 1][j] + 1;
        }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def minimumOperations(self, grid: list[list[int]]) -> int:
    ans = 0

    for j in range(len(grid[0])):
      for i in range(1, len(grid)):
        if grid[i][j] <= grid[i - 1][j]:
          ans += grid[i - 1][j] - grid[i][j] + 1
          grid[i][j] = grid[i - 1][j] + 1

    return ans