xinyu04

导航

[Google] LeetCode 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.

Solution

每次损失的为相邻两行纵坐标差的绝对值。考虑自底向上,从最后一层开始。如何求出每个位置的实际贡献呢?其实转移很简单,我们只需要考虑相邻的元素即可:

\[dp[i]=\max(dp[i], dp[i-1]-1) \]

再接着反向来一遍即可。最后加上下一层的数,直到第一层。

点击查看代码
class Solution {
private:
    long long dp[100002];
    long long ans = 0;
public:
    long long maxPoints(vector<vector<int>>& points) {
        int r = points.size(), c = points[0].size();
        for(int j=0;j<c;j++){
            dp[j] = points[r-1][j];
        }
        
        for(int i=r-2;i>=0;i--){
            // bottom to up
            for(int j=1;j<c;j++){
                dp[j] = max(dp[j], dp[j-1]-1);
            }
            for(int j=c-2;j>=0;j--){
                dp[j] = max(dp[j], dp[j+1]-1);
            }
            for(int j=0;j<c;j++)dp[j]+=points[i][j];
        }
        for(int j=0;j<c;j++)ans=max(ans, dp[j]);
        return ans;
    }
};

posted on 2022-08-22 05:15  Blackzxy  阅读(26)  评论(0编辑  收藏  举报