[LeetCode] Maximum Number of Points with Cost

1937. Maximum Number of Points with Cost

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.
  • new solution update 2022.05.13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
long long maxPoints(vector<vector<int>>& points) {
int m = points[0].size();
vector<long long> dp(m, 0), prv(m, 0);
for(auto& r : points) {
for(long long i = 0, ma = INT_MIN; i < m; i++) {
dp[i] = ma = max(ma - 1, prv[i]);
}
for(long long i = m - 1, ma = INT_MIN; i >= 0; i--) {
dp[i] = ma = max(ma - 1, dp[i]);
dp[i] += r[i];
}
swap(dp, prv);
}
return *max_element(begin(prv),end(prv));
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
long long maxPoints(vector<vector<int>>& points) {
long long sz(points[0].size());
vector<long long> cur(sz), prev(sz);
for(auto& p : points) {
for(long long i = 0, maxValue = 0; i < sz; ++i) {
cur[i] = maxValue = max(maxValue - 1, prev[i]);
}
for(long long i = sz - 1, maxValue = 0; i >= 0; --i) {
cur[i] = p[i] + max(maxValue = max(maxValue - 1, prev[i]), cur[i]);
}
swap(cur, prev);
}
return *max_element(begin(prev), end(prev));
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/27/PS/LeetCode/maximum-number-of-points-with-cost/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.