Max Points From Cards
MediumSame idea: minimise the untaken middle
Problem
Pick exactly k cards from either end of the row to maximize total points.
You pick k cards from either end — slide a window over which few you *leave behind* in the middle.
The idea
Whatever you do not take is a contiguous block of n-k cards, so the best score is the total minus the smallest such block. One fixed-size window pass answers it.
The trick
- Complement thinking: optimise the part you leave behind.
- Equivalent formulation: slide a prefix/suffix split across the k taken cards.
1
2
3
4
5
6
1
0
1
2
3
4
5
6
Step 1 of 6. Brute force: try taking every split of 3 cards from the two ends. Values: 1, 2, 3, 4, 5, 6, 1.
1/6
Brute force
timeO(k)spaceO(1)
Try every split.
1for (let front = 0; front <= k; front++) {2 const back = k - front;3 best = Math.max(best, sum(first front) + sum(last back));4}Input
- array
- [1, 2, 3, 4, 5, 6, 1]
Output
- best
- —
- answer
- —
Check yourself
3 quick questions about this walkthrough. A wrong answer costs nothing.
Examples
Example 1
- Input:
- cards = [1, 2, 3, 4, 5, 6, 1], k = 3
- Output:
- 12
- Explanation:
- Take 1 from the front and 6,5 from the back → 12.
Example 2
- Input:
- cards = [2, 2, 2], k = 2
- Output:
- 4
- Explanation:
- Any two cards give 4.
Example 3
- Input:
- cards = [9, 7, 7, 9, 7, 7, 9], k = 7
- Output:
- 55
- Explanation:
- Taking every card sums to 55.
Practice this problem:LeetCode(opens in a new tab)Search GeeksforGeeks(opens in a new tab)
Finished the walkthrough? Add it to your streak.