Minimum Operations to Make All Grid Elements Equal Problem
Description
LeetCode Problem 3888.
You are given a 2D integer array grid of size m × n, and an integer k.
In one operation, you can:
- Select any
k x ksubmatrix ofgrid, and - Increment all elements inside that submatrix by 1.
Return the minimum number of operations required to make all elements in the grid equal. If it is not possible, return -1.
A submatrix (x1, y1, x2, y2) is a matrix that forms by choosing all cells matrix[x][y] where x1 <= x <= x2 and y1 <= y <= y2.
Example 1:
Input: grid = [[3,3,5],[3,3,5]], k = 2
Output: 2
Explanation:
Choose the left 2 x 2 submatrix (covering the first two columns) and apply the operation twice.
- After 1 operation: [[4, 4, 5], [4, 4, 5]]
- After 2 operations: [[5, 5, 5], [5, 5, 5]]
All elements become equal to 5. Thus, the minimum number of operations is 2.
Example 2:
Input: grid = [[1,2],[2,3]], k = 1
Output: 4
Explanation:
Since k = 1, each operation increments a single cell grid[i][j] by 1. To make all elements equal, the final value must be 3.
- Increase grid[0][0] = 1 to 3, requiring 2 operations.
- Increase grid[0][1] = 2 to 3, requiring 1 operation.
- Increase grid[1][0] = 2 to 3, requiring 1 operation.
Thus, the minimum number of operations is 2 + 1 + 1 + 0 = 4.
Constraints:
1 <= m == grid.length <= 10001 <= n == grid[i].length <= 1000-10^5 <= grid[i][j] <= 10^51 <= k <= min(m, n)
Solution
Approach: Greedy with a 2D Difference Array
Operations only add, so the final value is T = max(grid) + s for some extra amount s >= 0. Scan the cells in row-major order. A cell (i, j) can only be covered later by operations whose top-left corner is above or to the left of it, so when the scan reaches it, the number of operations that must start there is forced: x = T - grid[i][j] - (increase already received). A 2D difference array tracks the increase from earlier operations in O(1) per cell.
Those counts are a linear function of s. Run the scan once with T = max(grid) and let x be the forced count at each cell. Raising the target by s adds s operations at every corner (i, j) where i and j are both multiples of k (counting from 0), and nothing anywhere else, because that is how a uniform increase of 1 is built from k x k tiles. Then:
- A cell where an operation cannot start (it would leave the grid) needs
x = 0. If it is a multiple-of-kcorner, that fixess = -x; all such cells must agree andscannot be negative. - A starting cell that is not a multiple-of-
kcorner needsx >= 0. - A starting cell that is a multiple-of-
kcorner needsx + s >= 0, sosmust be at least-x.
If no cell forces s, take the smallest allowed s. The answer is the sum of x over all valid starting cells plus s times the number of valid multiple-of-k corners, or -1 if any rule fails. (Trying only max(grid) and max(grid) + 1 is not enough: [[2,0,2],[2,0,2]] with k = 2 needs s = 2.)
Complexity: time O(mn), space O(mn), where m and n are the number of rows and columns.
class Solution:
def minOperations(self, grid: List[List[int]], k: int) -> int:
m, n = len(grid), len(grid[0])
mx = max(max(row) for row in grid)
diff = [[0] * (n + 2) for _ in range(m + 2)]
need = 0 # smallest extra amount s >= 0 the target must rise above max(grid)
forced = None # extra amount forced by corners that cannot start an operation
total = 0 # operations started at valid corners when the target is max(grid)
count = 0 # valid corners that always get the extra amount
for i in range(1, m + 1):
for j in range(1, n + 1):
diff[i][j] += diff[i - 1][j] + diff[i][j - 1] - diff[i - 1][j - 1]
x = mx - grid[i - 1][j - 1] - diff[i][j]
diff[i][j] += x
if i + k <= m + 1:
diff[i + k][j] -= x
if j + k <= n + 1:
diff[i][j + k] -= x
if i + k <= m + 1 and j + k <= n + 1:
diff[i + k][j + k] += x
grid_corner = (i - 1) % k == 0 and (j - 1) % k == 0
if i + k - 1 <= m and j + k - 1 <= n:
total += x
if grid_corner:
count += 1
need = max(need, -x)
elif x < 0:
return -1
elif grid_corner:
if forced is not None and forced != -x:
return -1
forced = -x
elif x != 0:
return -1
if forced is None:
return total + need * count
if forced < need:
return -1
return total + forced * count