Problem
You are given an m x n
integer matrix points
(0-indexed). Starting with 0
points, you want to maximize the number of points you can get from the matrix.
To gain points, you must pick one cell in each row. Picking the cell at coordinates (r, c)
will add points[r][c]
to your score.
However, you will lose points if you pick a cell too far from the cell that you picked in the previous row. For every two adjacent rows r
and r + 1
(where 0 <= r < m - 1
), picking cells at coordinates (r, c1)
and (r + 1, c2)
will subtract abs(c1 - c2)
from your score.
Return the maximum number of points you can achieve.
abs(x)
is defined as:
x
forx >= 0
.-x
forx < 0
.
Examples
Example 1:
$$ points = \begin{bmatrix} 1 & 2 & \colorbox{lightblue} 3 \\ 1 & \colorbox{lightblue} 5 & 1 \\ \colorbox{lightblue} 3 & 1 & 1 \end{bmatrix} $$
|
|
Example 2:
$$ grid = \begin{bmatrix} 1 & \colorbox{lightblue} 5 \\ 2 & \colorbox{lightblue} 3 \\ \colorbox{lightblue} 4 & 2 \end{bmatrix} $$
|
|
Solution
Method 1 - Simple Dynamic Programming
Code
|
|
Complexity
- ⏰ Time complexity:
O(m*n^2)
wherem
is number of rows, andn
is number of columns- This will result in TLE.
- 🧺 Space complexity:
O(m*n)
Method 2 - Optimal DP with left and right max
Previous solution was good, but we don’t want to literally compare every index in previous row to find the max points in the current row.
But if we look closely, the current row’s points for a certain index j, can also come from its left or right (inclusive). So, we can build two arrays - leftMax
and rightMax
, and focus on the maximum value coming from its left or right.
So, we can take leftMax[0] = prev[0]
, where prev is previous row.
Now, leftMax[1] = max(prev[1], leftMax[0] - 1)
Similarly, leftMax[2] = max(prev[2], leftMax[1] - 1)
Now, question is why it is sufficient to compareleftMax[1] - 1
and not leftMax[0] - 2
for filling in leftMax[2]
? And the reason is we already chose the optimal answer in leftMax[1]
.
Similarly, we build rightMax
from the right.
|
|
.
Approach
- Initialization: Use a DP array to keep track of the maximum points that can be achieved for each cell in the current row.
- Transition: For each cell in the current row, we need to consider all cells from the previous row. The points gained from the current cell should include the points from the previous cell minus the distance penalty.
- Optimization: To optimize the calculation, we can maintain two forward and backward sweeps to precompute the best points that can be achieved from any cell.
Code
|
|
Complexity
- Time:
O(m*n)
- Space:
O(m)