#1937

Maximum Number of Points with Cost

Medium
ArrayDynamic ProgrammingMatrixDynamic ProgrammingMatrix Traversal
LeetCode ↗

Approaches

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

Intuition

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

The optimal solution uses dynamic programming to build up the maximum score row by row, considering the penalties for column differences. This allows us to efficiently compute the maximum score without exploring all combinations.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a dp array to store the maximum points for each column in the current row.
  2. 2Step 2: For each row, compute the maximum points for each column by considering the previous row's points and applying the penalties for column differences.
  3. 3Step 3: Update the dp array for the current row and repeat until all rows are processed.
  4. 4Step 4: Return the maximum value from the last row of the dp array.
solution.py22 lines
1# Full working Python code
2
3def maxPoints(points):
4    m, n = len(points), len(points[0])
5    dp = points[0][:]
6    for i in range(1, m):
7        new_dp = [0] * n
8        max_left = [0] * n
9        max_right = [0] * n
10
11        max_left[0] = dp[0]
12        for j in range(1, n):
13            max_left[j] = max(max_left[j - 1], dp[j] + j)
14
15        max_right[n - 1] = dp[n - 1] - (n - 1)
16        for j in range(n - 2, -1, -1):
17            max_right[j] = max(max_right[j + 1], dp[j] - j)
18
19        for j in range(n):
20            new_dp[j] = points[i][j] + max(max_left[j] - j, max_right[j] + j)
21        dp = new_dp
22    return max(dp)

Complexity note: The time complexity is O(m * n) because we process each cell in the matrix once, while the space complexity is O(n) due to the dp array storing results for the current row.

  • 1Dynamic programming allows us to build solutions incrementally, reducing the need to explore all combinations.
  • 2Understanding how to manage penalties effectively is crucial for optimizing the score.

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