Maximum Points You Can Obtain from Cards - Problem

Imagine you're playing a strategic card game where you have a row of cards laid out in front of you, each with a specific point value. The twist? You can only pick cards from the very beginning or the very end of the row - no cherry-picking from the middle!

You're given an array cardPoints representing the points on each card, and you must take exactly k cards to maximize your score. Your goal is to determine the maximum possible sum of points you can achieve.

Example: If you have cards [1,2,3,4,5,6,1] and need to pick k=3 cards, you could take the first 3 cards (1+2+3=6), the last 3 cards (6+1+1=8), or a mix like first 1 and last 2 cards (1+1+1=3). The optimal strategy gives you 8 points!

Input: An integer array cardPoints and an integer k
Output: The maximum score (sum) you can obtain by picking exactly k cards from either end

Input & Output

example_1.py — Basic Case
$ Input: cardPoints = [1,2,3,4,5,6,1], k = 3
Output: 12
💡 Note: Take the last 3 cards: 5 + 6 + 1 = 12. This gives the maximum possible score.
example_2.py — Mixed Selection
$ Input: cardPoints = [2,2,2], k = 2
Output: 4
💡 Note: Take any 2 cards since they all have the same value: 2 + 2 = 4.
example_3.py — All Cards
$ Input: cardPoints = [9,7,7,9,7,7,9], k = 7
Output: 55
💡 Note: We must take all cards since k equals the array length: 9+7+7+9+7+7+9 = 55.

Constraints

  • 1 ≤ cardPoints.length ≤ 105
  • 1 ≤ cardPoints[i] ≤ 104
  • 1 ≤ k ≤ cardPoints.length
  • You must take exactly k cards
  • Cards can only be taken from the beginning or end of the array

Visualization

Tap to expand
1234561cardPoints = [1, 2, 3, 4, 5, 6, 1], k = 3Step 1: 1+2+3=6Step 2: 6-3+1=4Step 3: 4-2+6=8Step 4: 8-1+5=12Sliding Window Movement🎯 Maximum Score: 12Optimal strategy: Take 1 card from left (5) + 2 cards from right (6+1)
Understanding the Visualization
1
Initial Setup
Layout all cards in a row. You can only pick from the leftmost or rightmost positions.
2
Sliding Window
Start with k cards from left, then slide the selection window toward the right.
3
Efficient Updates
Instead of recalculating sums, just subtract the card being removed and add the new card.
4
Track Maximum
Keep track of the highest sum encountered during the sliding process.
Key Takeaway
🎯 Key Insight: Instead of trying all combinations separately, we can efficiently slide between taking all cards from one end to all cards from the other end, updating our running sum in O(1) time for each step!
Asked in
Meta 42 Amazon 38 Microsoft 29 Google 24
76.4K Views
High Frequency
~18 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen