Skip to content

Instantly share code, notes, and snippets.

@bhaveshmunot1
Created June 21, 2020 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhaveshmunot1/d374b40be70a25849977dd4f531e78da to your computer and use it in GitHub Desktop.
Save bhaveshmunot1/d374b40be70a25849977dd4f531e78da to your computer and use it in GitHub Desktop.
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