#3225

Maximum Score From Grid Operations

Hard
ArrayDynamic ProgrammingMatrixPrefix SumDynamic ProgrammingPrefix Sum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n^4)
O(n^2)
Space
O(n^2)
O(n)
💡

Intuition

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

The optimal solution uses dynamic programming to efficiently calculate the maximum score by keeping track of the best possible scores for each column and row. This reduces the need to simulate every operation explicitly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a DP table to store the maximum score achievable for each column.
  2. 2Step 2: Iterate through each cell in the grid and update the DP table based on the current cell's value and the previous scores.
  3. 3Step 3: Calculate the final score by summing the values from the DP table.
solution.py10 lines
1def maxScore(grid):
2    n = len(grid)
3    dp = [0] * n
4    for j in range(n):
5        for i in range(n):
6            if i > 0:
7                dp[j] += grid[i][j]
8            if j > 0:
9                dp[j] = max(dp[j], dp[j - 1])
10    return sum(dp)

Complexity note: The time complexity is O(n^2) because we iterate through each cell in the grid once. The space complexity is O(n) due to the DP array used to store the maximum scores for each column.

  • 1The score is maximized by strategically choosing which columns to color.
  • 2Dynamic programming allows us to build solutions incrementally, reducing redundant calculations.

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