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 of grid, 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 <= 1000
1 <= n == grid[i].length <= 1000
-105 <= grid[i][j] <= 105
1 <= k <= min(m, n)
Solutions
Solution 1: 2D Difference Array + Greedy
Since the operation can only increase the value of elements, all elements in the final grid must be equal to some target value \(T\), and \(T \ge \max(\textit{grid})\).
Start traversing the grid from the top-left corner \((0, 0)\). For any position \((i, j)\), if its current value is less than \(T\), since subsequent operations (with a more rightward or downward position as the top-left corner) cannot cover \((i, j)\), it is necessary to perform \(T - \text{current\_val}\) operations at the current position, each using \((i, j)\) as the top-left corner of a \(k \times k\) increment operation.
If each operation traverses the \(k \times k\) region, the complexity will reach \(O(m \cdot n \cdot k^2)\). We can use a 2D difference array \(\textit{diff}\) to record the operations. By maintaining the 2D prefix sum of \(\textit{diff}\) in real time, we can obtain the cumulative increment at the current position in \(O(1)\) time, and update the future impact of a \(k \times k\) region in \(O(1)\) time.
In most cases, \(T = \max(\textit{grid})\) is sufficient. However, in some cases where \(k \times k\) regions overlap, a smaller \(T\) may cause the middle positions to be passively increased beyond \(T\). According to mathematical consistency, if both \(T = \max(\textit{grid})\) and \(T = \max(\textit{grid}) + 1\) are not feasible, then it is impossible to flatten the grid using \(k \times k\) operations.
The time complexity is \(O(m \times n)\) and the space complexity is \(O(m \times n)\), where \(m\) and \(n\) are the number of rows and columns of the grid, respectively.