#3276

Select Cells in Grid With Maximum Score

Hard
ArrayDynamic ProgrammingBit ManipulationMatrixBitmaskDynamic ProgrammingBit Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n * m * 2^n)
Space
O(1)
O(2^n)
💡

Intuition

Time O(n * m * 2^n)Space O(2^n)

The optimal solution uses dynamic programming with bit manipulation to efficiently track selected cells across rows. By sorting the cells and using a bitmask to represent selected rows, we can maximize the score while ensuring uniqueness.

⚙️

Algorithm

4 steps
  1. 1Step 1: Flatten the grid into a list of tuples containing (value, row, col).
  2. 2Step 2: Sort this list by value in descending order.
  3. 3Step 3: Use a dynamic programming array where dp[mask] represents the maximum score achievable with the selected rows represented by 'mask'.
  4. 4Step 4: Iterate through the sorted list and update the dp array based on the current cell's row and value.
solution.py10 lines
1def maxScore(grid):
2    from itertools import product
3    n, m = len(grid), len(grid[0])
4    cells = sorted([(grid[i][j], i, j) for i in range(n) for j in range(m)], reverse=True)
5    dp = [0] * (1 << n)
6    for value, row, col in cells:
7        for mask in range((1 << n) - 1, -1, -1):
8            if (mask & (1 << row)) == 0:
9                dp[mask | (1 << row)] = max(dp[mask | (1 << row)], dp[mask] + value)
10    return max(dp)

Complexity note: The time complexity is O(n * m * 2^n) because we iterate through all cells and update the dp array for each possible selection of rows represented by the bitmask.

  • 1Sorting cells by value helps prioritize higher scores.
  • 2Using bit manipulation allows efficient tracking of selected rows.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.