Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Leetcode #1423: Maximum Points You Can Obtain from Cards (https://interviewrecipes.com/leetcode-1423)
class Solution {
public:
int maxScore(vector<int>& cardPoints, int k) {
int n = cardPoints.size();
vector<int> cumulativeSumFront(n+1, 0); // For easier indexing, add an extra element.
vector<int> cumulativeSumBack(n+1, 0); // For easier indexing, add an extra element.
for (int i=0; i<n; i++) {
cumulativeSumFront[i+1] = cumulativeSumFront[i] + cardPoints[i];
}
for (int i=n-1; i>=0; i--) {
cumulativeSumBack[i] = cumulativeSumBack[i+1] + cardPoints[i];
}
// Reversing is optional. I reversed it so that it would be easy
// to access sum of last (k-i) elements by just indexing at [k-i]
// Otherwise, I would have had to index it at [n-k+i] which would
// have made it difficult to read.
reverse(cumulativeSumBack.begin(), cumulativeSumBack.end());
int answer = 0;
for(int i=0; i<=k; i++) {
answer = max(answer,
cumulativeSumFront[i] // Sum of 'i' cards from the front.
+ cumulativeSumBack[k-i]); // Sum of 'k-i' cards from the back.
}
return answer;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.