Understanding the Problem
We are given an array called cardPoints
, and an integer k
. Imagine you are playing a game where you can pick exactly k
cards, but only from the start or end of the array—never from the middle.
Your goal is to get the maximum possible score by picking k
cards in total, from either end. The score is simply the sum of the selected cards.
For example, given:
cardPoints = [1, 2, 3, 4, 5, 6, 1], k = 3
You can choose the cards [1, 6, 5]
(from end and start), and their sum is 12
. This is the highest possible score with 3 cards.
Step-by-Step Solution with Example
Step 1: Understand the Brute Force Approach
If we try every combination of k
cards from the front and back, the number of possibilities is large. For example:
- Take all 3 cards from the front: [1, 2, 3]
- Take 2 from front and 1 from back: [1, 2, 1]
- Take 1 from front and 2 from back: [1, 6, 1]
- Take all 3 from the back: [6, 1, 5]
We can’t afford to try all combinations for large arrays. So we need an efficient method.
Step 2: Use Sliding Window Intuition
Here’s the key trick: instead of choosing which k
cards to take, we can think of which n-k
cards to leave out in the middle. Why?
Because you’re only allowed to pick cards from the two ends. So the cards you don’t pick are a continuous segment in the middle of the array.
Step 3: Calculate Total Sum and Find Minimum Middle Window
We first calculate the total sum of all the cards — this is the score if we could pick all cards.
Then, we find the minimum sum of any subarray of length n - k
(i.e., the unpicked cards). We subtract this from the total to get the maximum score.
cardPoints = [1, 2, 3, 4, 5, 6, 1], k = 3
Total cards = 7
We need to skip a window of 7 - 3 = 4 cards.
Try all subarrays of length 4:
[1, 2, 3, 4] → sum = 10
[2, 3, 4, 5] → sum = 14
[3, 4, 5, 6] → sum = 18
[4, 5, 6, 1] → sum = 16
Minimum sum = 10 (skip these 4 cards)
Total sum = 1+2+3+4+5+6+1 = 22
Max score = 22 - 10 = 12
Step 4: Code It with Sliding Window
We can use a sliding window of size n - k
to compute this efficiently without checking all subarrays manually.
Edge Cases
- k = cardPoints.length: You take all the cards, return the total sum.
- k = 0: You take no cards, score is 0.
- All elements are equal: Any selection of
k
cards will result in the same total score.
- Large values at both ends: Choosing from both ends should be considered (e.g., [1000, 1, 1, 1, 1000]).
Final Thoughts
This is a classic example of converting a selection problem into a window-based optimization. Instead of brute-force checking all combinations of taking cards from both ends, we slide a window over the part we skip and subtract it from the total. This makes the solution efficient and elegant.
Sliding window techniques are powerful when the problem involves contiguous subarrays or a fixed number of operations across a range. Always look for ways to turn the problem "inside out" like we did here.
Comments
Loading comments...