Minimum Number of Operations to Satisfy Conditions Problem
Description
LeetCode Problem 3122.
You are given a 2D matrix grid of size m x n. In one operation, you can change the value of any cell to any non-negative number. You need to perform some operations such that each cell grid[i][j] is:
- Equal to the cell below it, i.e.
grid[i][j] == grid[i + 1][j](if it exists). - Different from the cell to its right, i.e.
grid[i][j] != grid[i][j + 1](if it exists).
Return the minimum number of operations needed.
Example 1:
Input: grid = [[1,0,2],[1,0,2]]
Output: 0
Explanation:

All the cells in the matrix already satisfy the properties.
Example 2:
Input: grid = [[1,1,1],[0,0,0]]
Output: 3
Explanation:

The matrix becomes [[1,0,1],[1,0,1]] which satisfies the properties, by doing these 3 operations:
- Change grid[1][0] to 1.
- Change grid[0][1] to 0.
- Change grid[1][2] to 1.
Example 3:
Input: grid = [[1],[2],[3]]
Output: 2
Explanation:

There is a single column. We can change the value to 1 in each cell using 2 operations.
Constraints:
1 <= n, m <= 10000 <= grid[i][j] <= 9
Solution
Approach: Dynamic Programming
Each column must become a single digit, and neighbouring columns must use different digits. Cell values are only 0 to 9, so it is enough to try those ten digits for every column.
Let f[i][j] be the minimum number of changes for columns 0..i when column i is all j. Column i costs m - cnt[j] (every cell not already j), where cnt[j] is how many cells of the column equal j. Then f[i][j] = min over k != j of f[i-1][k] + m - cnt[j], and for the first column f[0][j] = m - cnt[j]. The answer is the smallest f[n-1][j].
Complexity: O(n(m + C^2)) time and O(nC) space, with C = 10 digits.
from math import inf
class Solution:
def minimumOperations(self, grid: List[List[int]]) -> int:
m, n = len(grid), len(grid[0])
f = [[inf] * 10 for _ in range(n)]
for i in range(n):
cnt = [0] * 10
for j in range(m):
cnt[grid[j][i]] += 1
if i == 0:
for j in range(10):
f[i][j] = m - cnt[j]
else:
for j in range(10):
for k in range(10):
if k != j:
f[i][j] = min(f[i][j], f[i - 1][k] + m - cnt[j])
return min(f[-1])