LeetCode in Kotlin

3402. Minimum Operations to Make Columns Strictly Increasing

Easy

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:

Example 2:

Input: grid = [[3,2,1],[2,1,0],[1,2,3]]

Output: 12

Explanation:

Constraints:

Solution

class Solution {
    fun minimumOperations(grid: Array<IntArray>): Int {
        var ans = 0
        for (c in grid[0].indices) {
            for (r in 1..<grid.size) {
                if (grid[r][c] <= grid[r - 1][c]) {
                    ans += grid[r - 1][c] + 1 - grid[r][c]
                    grid[r][c] = grid[r - 1][c] + 1
                }
            }
        }
        return ans
    }
}