和接雨水很像,虽然两道题都尝试暴力之后超时了
class Solution {
public:
long long maxPoints(vector<vector<int>>& points) {
int m = points.size();
int n = points[0].size();
vector<long long> pre(n); //pre(n)是指上一层的状态
for (int i = 0; i < m; ++i) { //
vector<long long> cur(n); //cur(n)是这一层的状态
long long best = LLONG_MIN;
// 正序遍历
for (int j = 0; j < n; ++j) {
//这个best是正序遍历过程中,找到的上一层最佳值
//因为是正序遍历,j >= j',-abs(j - j') = j' - j,所以此处是 + j(其实是j'),两行的j是不同的含义
//j的值是固定的当前列,但是j'的值是在遍历过程中不断变化的
best = max(best, pre[j] + j);
//这里best里的是最佳值中的j',j是固定的当前列
cur[j] = max(cur[j], best + points[i][j] - j);
}
best = LLONG_MIN;
// 倒序遍历
for (int j = n - 1; j >= 0; --j) {
//倒序遍历j' > j,-abs(j - j') = j - j',所以此处是 - j,如果best不变的话,就相当于- j'
best = max(best, pre[j] - j);
cur[j] = max(cur[j], best + points[i][j] + j);
}
pre = move(cur);
}
return *max_element(pre.begin(), pre.end());
}
};