Select Cells in Grid With Maximum Score Problem
Description
LeetCode Problem 3276.
You are given a 2D matrix grid consisting of positive integers.
You have to select one or more cells from the matrix such that the following conditions are satisfied:
- No two selected cells are in the same row of the matrix.
- The values in the set of selected cells are unique.
Your score will be the sum of the values of the selected cells.
Return the maximum score you can achieve.
Example 1:
Input: grid = [[1,2,3],[4,3,2],[1,1,1]]
Output: 8
Explanation:

We can select the cells with values 1, 3, and 4 that are colored above.
Example 2:
Input: grid = [[8,7,6],[8,3,2]]
Output: 15
Explanation:

We can select the cells with values 7 and 8 that are colored above.
Constraints:
1 <= grid.length, grid[i].length <= 101 <= grid[i][j] <= 100
Solution
Approach: Bitmask Dynamic Programming
Values are at most 100 and there are at most 10 rows. Let f[i][j] be the best score using only values 1..i, where j is the set of rows already used. First record, for each value, the rows in which it appears.
For each i and j, either skip the value i (f[i][j] = f[i-1][j]), or, for each row k in which i appears and that is in j, take it: f[i-1][j without k] + i. The answer is f[max][all rows].
Complexity: O(m 2m mx) time and O(mx 2m) space, where m is the number of rows and mx the largest value.
from collections import defaultdict
class Solution:
def maxScore(self, grid: List[List[int]]) -> int:
g = defaultdict(set)
mx = 0
for i, row in enumerate(grid):
for x in row:
g[x].add(i)
mx = max(mx, x)
m = len(grid)
f = [[0] * (1 << m) for _ in range(mx + 1)]
for i in range(1, mx + 1):
for j in range(1 << m):
f[i][j] = f[i - 1][j]
for k in g[i]:
if j >> k & 1:
f[i][j] = max(f[i][j], f[i - 1][j ^ 1 << k] + i)
return f[-1][-1]