里面的left和right数组意义没写明确,我个人理解是
left[i]: for ith position in current row, the max points one can get from previous rows if we pick points only in the left side of this position in previous row.
right[i]: 对于现在最新的row上的第i个元素,如果我们只在上一row上取现在这个点右边的元素的话,前面所有row能取得的最高分.
但这题我没办法自己想到这个解法,没见过也不知道为什么会有left right这个思路,原始的DP会有O(M*N^2)的time complexity, 所以目前的理解只能是为了提高时间复杂度对问题的分解。 如果想要我习得这个思维,估计需要更多同类题目的练习。
class Solution {
public:
long long maxPoints(vector<vector<int>>& points) {
long long m = points.size();
long long n = points[0].size();
// prev[i] max points from prev rows if we pick ith element in this row
vector<long long> prev(n);
// max points we get from first row if we pick ith element in this row
for (int i = 0; i < n; i++){
prev[i] = points[0][i];
}
for (int i = 0; i < m - 1; i++){
vector<long long> left(n, 0), right(n, 0), cur(n, 0);
left[0] = prev[0];
right[n - 1] = prev[n - 1];
for (int j = 1; j < n; j++){
left[j] = max(left[j-1]-1, prev[j]);
}
for (int j = n-2; j >= 0; j--){
right[j] = max(right[j+1]-1, prev[j]);
}
for (int j = 0; j < n; j++){
cur[j] = max(left[j], right[j]) + points[i+1][j];
}
prev = cur;
}
long long res = 0;
for (int i = 0; i < prev.size(); i++){
res = max(res, prev[i]);
}
return res;
}
};