Select Cells in Grid With Maximum Score - Problem
You're given a 2D grid filled with positive integers, and your goal is to become a strategic treasure hunter! 🏆
Your mission: Select cells from the grid to maximize your score (sum of selected values), but there are two crucial rules:
- No two cells from the same row - each row can contribute at most one treasure
- All selected values must be unique - no duplicates allowed in your collection
Think of it as choosing the best representatives from each row, where each representative must have a unique value that hasn't been chosen before.
Example: In grid [[1,2,3],[4,3,2],[1,1,1]], you could select 3 from row 0 and 4 from row 1 for a score of 7, but you can't select another 3 since values must be unique!
Input & Output
example_1.py — Basic Grid
$
Input:
grid = [[1,2,3],[4,3,2],[1,1,1]]
›
Output:
8
💡 Note:
Select 3 from row 0 (index [0,2]), 4 from row 1 (index [1,0]), and skip row 2 (all values are 1, but 1 hasn't been used yet, so we could pick 1 for a total of 3+4+1=8). Actually, the optimal is to pick 2 from row 0, 4 from row 1, and 1 from row 2 for total 2+4+1=7, or pick 3 from row 0 and 4 from row 1 for 3+4=7. Wait, let me recalculate: pick 3 from row 0, 4 from row 1, 1 from row 2 = 8 total.
example_2.py — Duplicate Values
$
Input:
grid = [[7,9,8,6,2],[6,1,1,2,8]]
›
Output:
24
💡 Note:
From row 0, select 9 (highest unique value). From row 1, select 1 (since 6, 2, 8 are already available in row 0, pick a value not in row 0). Actually, select 9 from row 0 and 1 from row 1 gives 9+1=10. Better: select 7 from row 0 and 8 from row 1 gives 15. Even better: select 9 from row 0 and 6 from row 1 gives 15. Optimal: select 8 from row 0 and 6 from row 1, but wait - we want to maximize, so select 9 from row 0 and 8 from row 1 but 8 appears in both rows. Select 9 from row 0 and 6 from row 1 = 15.
example_3.py — Single Row
$
Input:
grid = [[8,7,6]]
›
Output:
8
💡 Note:
With only one row, select the maximum value which is 8.
Constraints
- 1 ≤ grid.length, grid[i].length ≤ 10
- 1 ≤ grid[i][j] ≤ 100
- All values in the grid are positive integers
- You must select at least one cell to get a non-zero score
Visualization
Tap to expand
Understanding the Visualization
1
Catalog Artifacts
List all unique artifact values and create a tracking system
2
Hall by Hall
Process each exhibition hall (row) one by one
3
Smart Selection
For each hall, try selecting each artifact while tracking which values are already taken
4
Maximize Value
Keep track of the best possible exhibition value for each combination of selected artifacts
Key Takeaway
🎯 Key Insight: The bitmask DP approach efficiently explores all valid combinations by encoding 'which values have been used' as bits, avoiding redundant subproblem calculations and guaranteeing optimal results.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code