Maximum Points You Can Obtain from Cards - Problem

There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints.

In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.

Your score is the sum of the points of the cards you have taken.

Given the integer array cardPoints and the integer k, return the maximum score you can obtain.

Input & Output

Example 1 — Basic Case
$ Input: cardPoints = [1,2,3,4,5,6,1], k = 3
Output: 12
💡 Note: Take 3 cards from right end: [5,6,1] gives sum = 12. This is better than other combinations like taking 1 from left [1] and 2 from right [6,1] which gives 1+6+1=8.
Example 2 — Mixed Selection
$ Input: cardPoints = [2,2,2], k = 2
Output: 4
💡 Note: Can take 2 cards from left [2,2] = 4, or 2 cards from right [2,2] = 4, or 1 from each end [2,2] = 4. All give the same result.
Example 3 — All Cards
$ Input: cardPoints = [9,7,7,9,7,7,9], k = 7
Output: 55
💡 Note: Take all cards since k equals array length: 9+7+7+9+7+7+9 = 55

Constraints

  • 1 ≤ cardPoints.length ≤ 105
  • 1 ≤ cardPoints[i] ≤ 104
  • 1 ≤ k ≤ cardPoints.length

Visualization

Tap to expand
Maximum Points from Cards: Pick k=3 from EdgesCan only pick from ends:1234561cardPoints = [1,2,3,4,5,6,1], k = 3Option 1: 0 left + 3 right = 0 + (5+6+1) = 12Option 2: 1 left + 2 right = 1 + (6+1) = 8Option 3: 2 left + 1 right = (1+2) + 1 = 4Option 4: 3 left + 0 right = (1+2+3) + 0 = 6Maximum: 12
Understanding the Visualization
1
Input
Array of card points and k cards to pick
2
Process
Try different combinations of left and right selections
3
Output
Maximum possible sum from k edge cards
Key Takeaway
🎯 Key Insight: Maximum edge sum = Total sum - Minimum middle sum (sliding window approach)
Asked in
Amazon 15 Microsoft 12 Google 8 Facebook 6
89.0K Views
Medium Frequency
~15 min Avg. Time
2.5K 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