Minimum Increments to Equalize Grid
You are given an m x n integer matrix grid and an integer k.
In one operation, you may choose any contiguous k x k submatrix of grid and increase every element inside that submatrix by 1.
Return the minimum number of operations needed to make all elements of the grid equal. If it is impossible, return -1.
A k x k submatrix is formed by selecting a top-left cell (r, c) such that all cells from rows r to r + k - 1 and columns c to c + k - 1 lie inside the grid.
Example 1:
Input: grid = [[1,1,3],[1,1,3]], k = 2
Output: 2
Explanation:
Choose the 2 x 2 submatrix covering the first two columns and apply the operation twice.
- After 1 operation: [[2,2,3],[2,2,3]]
- After 2 operations: [[3,3,3],[3,3,3]]
So, the minimum number of operations is 2.
Example 2:
Input: grid = [[2,4],[3,5]], k = 1
Output: 6
Explanation:
When k = 1, each operation increases exactly one cell by 1.
To make all elements equal, the best final value is 5.
- Increase 2 to 5 → 3 operations
- Increase 4 to 5 → 1 operation
- Increase 3 to 5 → 2 operations
- Increase 5 to 5 → 0 operations
Total operations = 3 + 1 + 2 + 0 = 6.
Now Your Turn!
Pick the correct output for the given inputInput: grid = [[1,2],[2,1]], k = 2
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= m == grid.length <= 1000
- 1 <= n == grid[i].length <= 1000
- grid[i].length == n
- -105 <= grid[i][j] <= 105
- 1 <= k <= min(m, n)