There are n cards in a row, and cardPoints[i] is the number of points on the i-th card. In one move you take a card from the beginning or the end of the row, and you make exactly k such moves.
Your score is the sum of the points on the cards you take. Return the maximum score you can achieve.
Input: cardPoints = [1,2,3,4,5,6,1], k = 3 Output: 12 The best is to take the last card (1) and two from the front... in fact take 1, 6, 5 from the ends for 12. Equivalently, leave the min-sum block [1,2,3,4]=10, so 22-10=12.
Input: cardPoints = [2,2,2], k = 2 Output: 4 Any two cards sum to 4.
- 1 <= cardPoints.length <= 10^5 - 1 <= cardPoints[i] <= 10^4 - 1 <= k <= cardPoints.length
You take k cards from the two ends — which is fiddly to reason about directly. Flip it: the cards you leave behind are always a single contiguous block of size n - k in the middle. Minimizing the sum of that block maximizes what you take. And the minimum-sum block of a fixed size is a textbook fixed sliding window.
“Can I take from both ends?”
Yes — each of the k moves takes the current first or last card, in any mix.
“Do I take exactly k cards?”
Yes, exactly k — no fewer.
“What if k equals n?”
You take every card, so the answer is the total sum.
Taking k cards from the ends means leaving a contiguous block of n - k cards in the middle.
My score is the total minus that leftover block, so I want the leftover block's sum as small as possible.
That's the minimum-sum window of a fixed size — a single sliding-window pass.
Worked example — cardPoints = [1,2,3,4,5,6,1], k = 3
total = 22, leftover window size = n - k = 4 windows of size 4: [1,2,3,4]=10 [2,3,4,5]=14 [3,4,5,6]=18 [4,5,6,1]=16 min leftover = 10 answer = 22 - 10 = 12
Taking from the ends always leaves a single contiguous block of size n - k. That fixed size is what makes a constant-width sliding window apply.
score = total - leftover. The total is fixed, so the best score comes from the smallest possible leftover-window sum.
Move the window one step by adding the entering card and subtracting the leaving card — no re-summing — giving an O(n) scan.
| Try every split | Minimize leftover window | |
|---|---|---|
| Idea | Take i from the left and k-i from the right, for all i | total minus the min-sum window of size n-k |
| Time | O(k) | O(n) |
| Space | O(1) | O(1) |
Both are linear and correct; the min-window view is the cleaner sliding-window framing this chapter is about. Full code is in the Approaches selector below.
Key takeaway
Taking k cards from the ends leaves a contiguous block of size n - k. Your score is total - leftover, so minimize the leftover block: slide a fixed-size window of width n - k, track its sum with one add and one subtract per step, and subtract the smallest sum from the total.
w = n - k if w == 0: return total window = sum of first w cards; minWindow = window slide window across the array, updating minWindow return total - minWindow