240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 22 | Leetcode 1423. Maximum Points You Can Obtain from Cards

题解

Medium

方法:动态规划

左边 k 个数连续求和,右边倒数 k 个数连续求和。然后,两个数组收尾相加,就是 k 次首、尾抽牌的所有组合。

class Solution {
public:
    int maxScore(vector<int>& cardPoints, int k) {
        vector<int> left(1, 0), right(1, 0);
        
        for(int i = 0; i < k; i++) {
            left.push_back(left.back() + cardPoints[i]);
            right.push_back(right.back() + cardPoints[cardPoints.size()-1-i]);
        }
        
        int max_sum = 0;
        
        for(int i = 0; i < k+1; i++) {
           max_sum = max(max_sum, left[i] + right[k-i]);
        }
        
        return max_sum;
    }
};
posted @ 2020-10-10 09:25  CasperWin  阅读(163)  评论(0编辑  收藏  举报