621. Maximum Points You Can Obtain from Cards
A row of cards lies on the table, the value of each written in the array card_points. You must pick up exactly k cards, and every pick must come from one of the two ends of the remaining row — the current leftmost or the current rightmost card. Your score is the sum of the cards you pick up.
The function receives card_points and the integer k, and returns the maximum score you can reach.
Because each pick shortens the row from an end, any final selection is always some i cards off the front plus k − i cards off the back.
Example 1:
Input: card_points = [5, 1, 2, 8, 3, 4], k = 3
Output: 15
Explanation: Take all three picks from the back: 4, then 3, then 8, scoring 15. Any mix touching the front trades an 8 or a 4 for a 5, 1, or 2.
Example 2:
Input: card_points = [2, 9, 1, 1, 6], k = 2
Output: 11
Explanation: The best two picks are both from the front: 2 + 9 = 11. Splitting (2 + 6 = 8) or taking both from the back (1 + 6 = 7) scores less.
Constraints:
- 1 ≤ card_points.length ≤ 10⁵
- 1 ≤ card_points[i] ≤ 10⁴
- 1 ≤ k ≤ card_points.length
Hints:
The picks never come from the middle: whatever you do, you end up with i cards from the front and k − i from the back, for some i between 0 and k. That is only k + 1 candidate selections.
Precompute prefix sums (or running front/back totals) so each candidate is evaluated in O(1) instead of re-summing.
Flip the problem: taking k cards from the ends means *leaving* a contiguous window of exactly n − k cards in the middle. Maximizing what you take is minimizing the sum of that window — a fixed-size sliding window.
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: card_points = [5, 1, 2, 8, 3, 4], k = 3
Expected output: 15