Problem Description
Given an m x n integer matrix points, pick one cell from each row so that your total score is maximized. If you select cell (r, c) in a row, you add points[r][c] to your score. However, for every two consecutive rows, you subtract the absolute difference of their column indices from your score (i.e. if you picked c1 in row r and c2 in row r+1, you subtract abs(c1 - c2)). The goal is to determine the maximum possible score.
Key Insights
- Use dynamic programming to store the best achievable score ending at each column.
- Transition between rows must incorporate the cost of changing columns, given by abs(c1 - c2).
- Precompute two helper arrays (left and right) for each row to capture the maximum score obtainable from left-to-right and right-to-left, effectively handling the absolute difference cost in O(n) time per row.
- This optimized transition allows for solving the problem efficiently without using a nested loop for cost computation.
Space and Time Complexity
Time Complexity: O(m * n), where m is the number of rows and n is the number of columns. Space Complexity: O(n), since only one-dimensional arrays (dp, left, right) are maintained for computations.
Solution
The solution involves dynamic programming by tracking the maximum score achievable at each cell of the current row. For each row beyond the first, two helper arrays, left and right, are computed:
- The left array is built by iterating from left to right, adjusting the score by subtracting 1 for each move to the right.
- The right array is built by iterating from right to left, similarly subtracting 1 for each move to the left. Then, for every cell in the new row, the best possible previous score is added from either the left or right helper array along with the current cell's points. This trick avoids the need for an inner loop to compute the absolute difference cost for every pair of columns, thereby optimizing the transition.