A row of cards each carries a point value, and you must take exactly k of them. On every pick you may only remove a card from the very front or the very back of the row. Choose your picks so the total of the chosen cards is as large as possible.
Instead of deciding which ends to draw from, flip the problem around: the cards you leave behind always form one contiguous block of size length minus k in the middle. Maximising what you take is the same as leaving behind the cheapest possible middle block.
Example 1
Input: cardPoints = [1,2,3,4,5,6,1], k = 3
Output: 12
Taking 1 from the front and 6 then 5 from the back collects 12 points, which is the best any three end-picks can do.
Example 2
Input: cardPoints = [9,7,7,9,7,7,9], k = 7
Output: 55
With k equal to the whole row, every card must be taken, so the answer is the total of all values.
Constraints
1 ≤ cardPoints.length ≤ 10^51 ≤ cardPoints[i] ≤ 10^41 ≤ k ≤ cardPoints.lengthSee the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI