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
.
Example 1:
Input: points = [[1,2,3],[1,5,1],[3,1,1]] 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.
思路:这个题是dp,但是brute force是M*N*N,需要 优化,优化就是数学公式展开,发现是个rollingmax,然后用O(1)去计算下一个值,这样优化到O(M*N);
brute force:
for(int i = 1; i < m; i++) {
for(int j = 0; j < n; j++) {
for(int k = 0; k < n; k++) {
dp[i][j] = Math.max(dp[i][j], dp[i - 1][k] + points[i][j] - Math.abs(j - k));
}
}
}
把绝对值展开:分别讨论 k <= j, j >= k ,发现前面的k变化是个rolling max,这样每步可以优化成O(1)
/*
dp[i - 1][k] + points[i][j] - Math.abs(j - k)
k <= j; k = 0, 1, 2,....j;
dp[i][j] = Math.max(dp[i][j], dp[i - 1][k] + k + points[i][j] - j ;
k >= j;
dp[i][j] = Math.max(dp[i][j], dp[i - 1][k] - k + points[i][j] + j);
*/
class Solution {
public long maxPoints(int[][] points) {
int m = points.length;
int n = points[0].length;
long[][] dp = new long[m][n];
// 1st row;
for(int j = 0; j < n; j++) {
dp[0][j] = points[0][j];
}
// calculate matrix;
// dp[i][j] = dp[i - 1][k] + points[i][j] - Math.abs(k - j);
// case 1: k <= j; dp[i][j] = dp[i - 1][k] + points[i][j] - (j - k); k = 0,1,2,3....j
// dp[i][j] = dp[i - 1][k] + k + points[i][j] - j;
// case 2: k >= j; dp[i - 1][k] + points[i][j] - k + j; k = j + 1,....n - 1;
// dp[i - 1][k] - k + points[i][j] + j;
for(int i = 1; i < m; i++) {
// k <= j;
long rollMax = Long.MIN_VALUE;
for(int j = 0; j < n; j++) {
rollMax = Math.max(rollMax, dp[i - 1][j] + j);
dp[i][j] = Math.max(dp[i][j], rollMax + points[i][j] - j);
}
// k >= j;
rollMax = Long.MIN_VALUE;
for(int j = n - 1; j >= 0; j--) {
rollMax = Math.max(rollMax, dp[i - 1][j] - j);
dp[i][j] = Math.max(dp[i][j], rollMax + points[i][j] + j);
}
}
long res = 0;
for(int j = 0; j < n; j++) {
res = Math.max(res, dp[m - 1][j]);
}
return res;
}
}
/*
dp[i - 1][k] + points[i][j] - Math.abs(j - k)
k <= j; k = 0, 1, 2,....j;
dp[i][j] = Math.max(dp[i][j], dp[i - 1][k] + k + points[i][j] - j ;
j >= k;
dp[i][j] = Math.max(dp[i][j], dp[i - 1][k] - k + points[i][j] + j);
*/