Maximum Points You Can Obtain from Cards
Master this topic with zero to advance depth.
Maximum Points You Can Obtain from Cards
You can take exactly k cards from either the beginning or the end of the row to maximize your point total.
Visual Representation
cardPoints = [1, 2, 3, 4, 5, 6, 1], k = 3
Take cards from ends (Total: 7, k: 3):
(1, 2) ... (1) Total: 4
(1) ... (6, 1) Total: 8
... ... (5, 6, 1) Total: 12 (MAX)
Trick: Minimize the sum of the remaining (n-k) cards!
Remaining window size = 7 - 3 = 4Examples
Level I: Brute Force
Intuition
Try all possible combinations of taking i cards from the left and k - i cards from the right (where 0 <= i <= k). For each combination, calculate the sum and track the maximum.
Thought Process
- Let
ibe the number of cards from the left end. - Then
k - icards must be taken from the right end. - Iterate
ifrom0tok. - Calculate
Sum = (Sum of first i) + (Sum of last k - i). - Tracking the maximum sum.
Detailed Dry Run
| Cards from Left | Cards from Right | Total Sum |
|---|---|---|
| 0 | 3 (5, 6, 1) | 12 |
| 1 (1) | 2 (6, 1) | 8 |
| 2 (1, 2) | 1 (1) | 4 |
| 3 (1, 2, 3) | 0 | 6 |
Level III: Optimal (Sliding Window)
Intuition
Thought Process
Selecting k cards from the ends is equivalent to leaving n - k contiguous cards in the middle. To maximize the end cards, we must minimize the sum of the middle cards. This turns it into a fixed-size sliding window problem on the inner subarray.
Patterns
- Inverse Goal: Instead of picking ends, find the minimum middle.
- Fixed Window: The middle part always has size
n - k.
Detailed Dry Run
| Window | Sum | Min Sum | Action |
|---|---|---|---|
| [1, 2, 3, 4] | 10 | 10 | Initial |
| [2, 3, 4, 5] | 14 | 10 | Slide |
| [3, 4, 5, 6] | 18 | 10 | Slide |
| [4, 5, 6, 1] | 16 | 10 | Slide |
⚠️ Common Pitfalls & Tips
While you can use recursion with memoization, the sliding window approach is much faster and uses O(1) extra space. The 'inverse' trick is the most important leap.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.