Maximum Points You Can Obtain from Cards

medium

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.

Hints

Taking k cards from the ends leaves what shape of cards in the middle?
The untaken cards form one contiguous block of size n - k.
Maximize your score by minimizing that block's sum — a fixed-size sliding window.

Common doubts

The taken cards come from both ends and aren't contiguous, but the untaken cards always form one contiguous block of size n - k — which a fixed window handles directly.
You always take exactly k cards, so you always leave exactly n - k, and that leftover block has constant width — the defining feature of a fixed sliding window.
Then the leftover window has size 0 — you take every card, so the answer is simply the total sum.

Interview follow-ups

Then you'd also consider smaller take-counts; but since all points are positive, taking exactly k is always at least as good, so it doesn't change the answer here.
The complement trick still works, but 'take exactly k' can now be worse than taking fewer — you'd compare the best leftover window across the relevant sizes.

Fun facts

  • Reframing 'pick from both ends' as 'a single contiguous leftover' is a recurring trick that converts awkward two-sided choices into one clean window.
  • The same fixed-window sum update — add one, drop one — underlies moving averages in signal processing.

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
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.
Example 2
Input: cardPoints = [2,2,2], k = 2
Output: 4
Any two cards sum to 4.
Constraints

- 1 <= cardPoints.length <= 10^5 - 1 <= cardPoints[i] <= 10^4 - 1 <= k <= cardPoints.length

Solve this problem →