Maximum Points From Cards

35 min · maxPointsCards()

A row of reward cards sits face up, but you can reach only its two ends. A valuable card in the middle becomes reachable only after the cards in front of it are gone.

Given an array cardPoints and an integer k, take exactly k cards. Each move removes either the front card or the back card from the remaining row. Return the largest total score you can collect.

A few ground rules:

  • You must take exactly k cards, not up to k.
  • After a card is removed, the next card on that side becomes the new end.
  • Every score is positive, and each card can be taken at most once.
  • The answer is at most 1_000_000_000, so it fits a signed 32-bit integer.

Constraints

  • 1 <= cardPoints.length <= 100_000
  • 1 <= cardPoints[i] <= 10_000
  • 1 <= k <= cardPoints.length

Hints

Count the possible splits

If you take i cards from the front, the other k - i must come from the back. That leaves only k + 1 front/back splits to compare.

Turn taken cards into leftovers

After removing cards only from the two ends, every card you leave behind forms one unbroken interior block. Its length is cardPoints.length - k.

Reverse the objective

Your score equals the total of all cards minus the sum of that interior block. Find the minimum-sum fixed window of length n - k, then subtract it from the total.

Follow-up

Can you evaluate all k + 1 front/back splits in O(k) time while keeping only O(1) extra space? Which formulation does less work when k is tiny compared with the row?

Visible cases

Examples

Example 1

ready
Input
cardPoints = [
  1,
  2,
  3,
  4,
  5,
  6,
  1
]
k = 3
Expected
12
Why
take the final three cards from the back: 5 + 6 + 1 = 12

Example 2

ready
Input
cardPoints = [
  2,
  2,
  2
]
k = 3
Expected
6
Why
k equals the row length, so every card is taken

Example 3

ready
Input
cardPoints = [
  9,
  1,
  1,
  9
]
k = 2
Expected
18
Why
one card from each end beats taking both from either side

Example 4

ready
Input
cardPoints = [
  5,
  4,
  3,
  2,
  1
]
k = 2
Expected
9
Why
taking the first two cards gives the largest total

Interview signal

Asked at

AmazonMetaGoogle
Loading editor

Console

ready to run

Ready to run.

4 cases are queued.

Run: visible + custom · Submit: full suite