Input: grid =[[3,2],[1,3],[3,4],[0,1]]Output: 15Explanation:
* To make the `0th` 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 `1st` column strictly increasing, we can apply 4 operations on `grid[3][1]`.
Input: grid =[[3,2,1],[2,1,0],[1,2,3]]Output: 12Explanation:
* To make the `0th` column strictly increasing, we can apply 2 operations on `grid[1][0]`, and 4 operations on `grid[2][0]`.* To make the `1st` column strictly increasing, we can apply 2 operations on `grid[1][1]`, and 2 operations on `grid[2][1]`.* To make the `2nd` column strictly increasing, we can apply 2 operations on `grid[1][2]`.
To make each column strictly increasing, for every cell below the first row, if its value is not greater than the cell above, increment it enough to be one more than the cell above. Sum all such increments for all columns.
classSolution {
public:int minOperations(vector<vector<int>>& grid) {
int m = grid.size(), n = grid[0].size(), ans =0;
for (int j =0; j < n; ++j) {
for (int i =1; i < m; ++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
funcminOperations(grid [][]int) int {
m, n:= len(grid), len(grid[0])
ans:=0forj:=0; j < n; j++ {
fori:=1; i < m; i++ {
ifgrid[i][j] <=grid[i-1][j] {
ans+=grid[i-1][j] -grid[i][j] +1grid[i][j] = grid[i-1][j] +1 }
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintminOperations(int[][] grid) {
int m = grid.length, n = grid[0].length, ans = 0;
for (int j = 0; j < n; j++) {
for (int i = 1; i < m; 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
15
16
classSolution {
funminOperations(grid: Array<IntArray>): Int {
val m = grid.size
val n = grid[0].size
var ans = 0for (j in0 until n) {
for (i in1 until m) {
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
classSolution:
defminOperations(self, grid: list[list[int]]) -> int:
m, n = len(grid), len(grid[0])
ans =0for j in range(n):
for i in range(1, m):
if grid[i][j] <= grid[i-1][j]:
ans += grid[i-1][j] - grid[i][j] +1 grid[i][j] = grid[i-1][j] +1return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnmin_operations(mut grid: Vec<Vec<i32>>) -> i32 {
let m = grid.len();
let n = grid[0].len();
letmut ans =0;
for j in0..n {
for i in1..m {
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;
}
}
}
ans
}
}