Sliding Window
Medium
Maximum Points You Can Obtain from Cards
Find the maximum score you can get by taking k cards from either end of the row.
20 min
Solve on LeetCodeProblem Understanding
There are several cards arranged in a row, and each card has an associated number of points. You can take exactly k cards.
Constraint: In each step, you can take one card from either the beginning or the end of the row.
Goal: keyimize the total points of the cards you have taken.
Example:
nums = [1, 2, 3, 4, 5, 6, 1],k = 3- Output:
12 - Explanation: Take
[1, 2]from left and[1]from right? Sum = 4.
Or take[1]from left and[6, 1]from right? Sum = 8.
Or take[5, 6, 1]from right? Sum = 12. (Max)
Algorithm Strategy
Instead of simulating every decision (Recursion/DP), which is slow, realize that we always select k cards total. If we take i cards from the left means we MUST take k - i cards from the right.
The Sliding Window Approach:
- Start: Assume we take all
kcards from the beginning (left side). Calculate thiscurrent_sum. - Slide: In each step, we give up one card from the left and take one card from the right.
- Subtract
card[k - 1 - i](the rightmost card of our left selection). - Add
card[n - 1 - i](the corresponding card from the end of the array).
- Subtract
- Track: Keep track of the maximum sum found during this sliding process.
Visual Walkthrough
Step 1 / 1
Initializing...
1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.ON THIS PAGE
- Problem Understanding
- Algorithm Strategy
- Visual Walkthrough
- Dry Run: [1, 2, 3, 4, 5, 6, 1], k=3
- Edge Cases & Tips
- Code Solution
- Complexity Analysis
Stop Guessing, Start Mastering.
Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.
