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 INPUT cardPoints array: 1 i=0 2 i=1 3 i=2 4 i=3 5 i=4 6 i=5 1 i=6 Parameters: k = 3 (cards to pick) n = 7 (total cards) Pick k cards from LEFT or RIGHT ends Left Right ALGORITHM STEPS 1 Sliding Window Idea Find min sum of (n-k) consecutive cards in middle 2 Calculate Total Sum total = 1+2+3+4+5+6+1 = 22 3 Slide Window (size n-k=4) Find minimum subarray sum Window 1: [1,2,3,4] = 10 Window 2: [2,3,4,5] = 14 Window 3: [3,4,5,6] = 18 Window 4: [4,5,6,1] = 16 MIN! 4 Calculate Result maxScore = total - minWindow maxScore = 22 - 10 = 12 Complexity: Time: O(n) Space: O(1) FINAL RESULT Optimal Selection: 1 PICK 2 PICK 3 PICK 4 5 6 1 Maximum Score 12 1 + 2 + 3 + 6 = 12 OK - Verified! Key Insight: Instead of trying all combinations of picking from left and right, use the sliding window technique. Taking k cards from ends = leaving (n-k) consecutive cards in middle. Minimize what we leave to maximize what we take. This converts a complex problem to a simple min subarray sum problem! TutorialsPoint - Maximum Points You Can Obtain from Cards | 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