Maximum Points You Can Obtain from Cards
1 approach, code in every language
Problem description
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.length
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Forklift Picks from the Crate Row is our own problem on the technique behind Maximum Points You Can Obtain from Cards: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free