[LeetCode] Maximum Points You Can Obtain from Cards

1423. Maximum Points You Can Obtain from Cards

There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints.

In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.

Your score is the sum of the points of the cards you have taken.

Given the integer array cardPoints and the integer k, return the maximum score you can obtain.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int maxScore(vector<int>& cardPoints, int k) {
int sum = accumulate(cardPoints.begin(), cardPoints.begin() + k, 0), res(sum), back(cardPoints.size() - 1);
if(k == cardPoints.size()) return res;
while (k) {
res = max(res, sum = sum - cardPoints[--k] + cardPoints[back--]);
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/06/20/PS/LeetCode/maximum-points-you-can-obtain-from-cards/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.