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 for x >= 0.-x for x < 0.Output: 9
Explanation:
The blue cells denote the optimal cells to pick, which have coordinates (0, 2), (1, 1), and (2, 0).
You add 3 + 5 + 3 = 11 to your score.
However, you must subtract abs(2 - 1) + abs(1 - 0) = 2 from your score.
Your final score is 11 - 2 = 9.
Output: 11
Explanation:
The blue cells denote the optimal cells to pick, which have coordinates (0, 1), (1, 1), and (2, 0).
You add 5 + 3 + 4 = 12 to your score.
However, you must subtract abs(1 - 1) + abs(1 - 0) = 1 from your score.
Your final score is 12 - 1 = 11.
The Brute Force approach for this problem involves considering every possible path through the matrix, calculating the cost for each path, and then returning the maximum cost found. This is achieved by iterating over the matrix in a row-wise manner, and for each cell in a given row, calculating the cost based on all possible previous cells from the row above, accounting for their respective penalties.
The naive way to solve this problem is to iterate over each row and for every cell in the current row, consider every possible previous cell in the row above. For each combination, we calculate the cost using the given formula, and we keep track of the maximum cost encountered thus far.
We can optimize the brute-force solution by utilizing dynamic programming to progressively build up the solution. We will keep a record of the maximum costs achievable for each cell, using information from the previous row. The idea is to avoid recalculating penalties for non-optimal choices by using pre-computed maximum values from the left and right neighbors.
To optimize our solution, we can pass through the matrix twice for each row. The first pass calculates the maximum possible score for each cell considering penalties from the left neighbor direction. The second pass does the same from the right neighbor direction. Thus, each cell will have the maximum score via the least penalized neighbor direction. By maintaining efficient transitions between computations, the solution is achieved more rapidly than the naive method.