Description
Solution
最终的方案一定是前缀+后缀,故
O
(
N
)
O(N)
O(N)前缀和枚举即可
Code
class Solution {
public:
int maxScore(vector<int>& cardPoints, int k) {
int sz = cardPoints.size();
vector<int>sum(sz);
for(int i = 0;i < sz;++i) {
if(i == 0) sum[i] = cardPoints[i];
else sum[i] = sum[i-1] + cardPoints[i];
}
if(k == sz) return sum[sz-1];
int res = sum[sz-1] - sum[sz-1-k];
for(int i = 0;i < k;++i) {
res = max(res, sum[i] + sum[sz-1] - sum[sz-k+i]);
}return res;
}
};