Maximum Points You Can Obtain from Cards
Medium · Sliding Window · Explanation and code example
Sliding Window
How it works
We can directly maintain a sliding window of size k that wraps around the array. Start by taking all k cards from the right end. Then slide the window: remove one card from the right and add one from the left, tracking the maximum sum as we go.
Steps
- Initialize the sum by taking the last
kcards (all from the right). - Use two pointers:
lstarting at0,rstarting atn - k. - Slide the window
ktimes:- Add
cardPoints[l]and subtractcardPoints[r]. - Update the maximum sum.
- Move both pointers forward.
- Add
- Return the maximum sum found.
Complexity
- Time complexity:
O(k) - Space complexity:
O(1)extra space.
Where
kis the number of cards to pick.
Things to watch for
Treating This as a Standard Two-Pointer Problem
Unlike typical two-pointer problems where pointers move toward each other, this problem requires taking cards from both ends that together form a contiguous "virtual" window. The cards you pick are not contiguous in the original array, which confuses many solvers into incorrect pointer movement logic.
Off-by-One Errors in Window Boundaries
When using the sliding window approach (finding minimum sum of n - k elements), incorrect boundary calculations are common. The window size is n - k, not k. Additionally, when indexing the right portion of the array, using n - right instead of the correct index offset leads to accessing wrong elements.
Forgetting the Edge Case When k Equals n
When k equals the array length, you must take all cards. The sliding window approach would have a window of size 0, which needs special handling to avoid division by zero or invalid array access. Simply return the total sum when k == n.
Python code example
from typing import List
class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
l, r = 0, len(cardPoints) - k
total = sum(cardPoints[r:])
res = total
while r < len(cardPoints):
total += cardPoints[l] - cardPoints[r]
res = max(res, total)
l += 1
r += 1
return res
C++ code example
class Solution {
public:
int maxScore(vector<int>& cardPoints, int k) {
int l = 0, r = cardPoints.size() - k;
int total = 0;
for (int i = r; i < cardPoints.size(); i++) {
total += cardPoints[i];
}
int res = total;
while (r < cardPoints.size()) {
total += cardPoints[l] - cardPoints[r];
res = max(res, total);
l++;
r++;
}
return res;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.