Maximum Points You Can Obtain from Cards Visualizer & Step-by-Step Algorithm Solution

Take exactly k cards from the two ends, exchanging one left card for one right card to find the maximum score.

Category: sliding-window | Difficulty: Medium

Tags: Array, Sliding Window, Prefix Sum

Maximum Points You Can Obtain from Cards

Card points ยท highlighted cards are taken
1
0
2
1
3
2
4
3
5
4
6
5
1
6
100%
state
n7
k3
sum0
left taken0
right taken0
Count Cards
1/21
Explanation

n = 7. Take exactly 3 cards from the ends. Every valid choice is a left prefix plus a right suffix; there are 4 splits to check.

Source Code
1function maxScore(cardPoints: number[], k: number): number {
2 const n = cardPoints.length;
3 let sum = 0;
4 for (let i = 0; i < k; i++) sum += cardPoints[i];
5
6 let best = sum;
7 for (let i = 1; i <= k; i++) {
8 sum += cardPoints[n - i] - cardPoints[k - i];
9 best = Math.max(best, sum);
10 }
11 return best;
12}