ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

[Google] LeetCode 1937 Maximum Number of Points with Cost

2022-08-22 05:30:08  阅读:191  来源: 互联网

标签:will Google int Number long Maximum cell points dp


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;
    }
};

标签:will,Google,int,Number,long,Maximum,cell,points,dp
来源: https://www.cnblogs.com/xinyu04/p/16611606.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有