Browse curriculum

FAANGPrep Sprint

Maximum Points You Can Obtain from Cards

Find the maximum score you can get by taking k cards from either end of the row.

Medium
20 min
Solve on LeetCode

Problem Understanding

A row of cards each carries a point value, and you must take exactly k of them.

Constraint: In each step, you can take one card from either the beginning or the end of the row.

Goal: maximize 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, we must take k - i cards from the right.

The Sliding Window Approach:

  1. Start: Assume we take all k cards from the beginning (left side). Calculate this current_sum.
  2. 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).
  3. Track: Keep track of the maximum sum found during this sliding process.

Visual Walkthrough

TAKE 3 · FRAME = CARDS LEFT IN THE MIDDLE

TAKE FROM LEFT

take

1

0

2

1

3

2

4

3

5

4

6

5

1

6

Left sum

1

Right sum

0

Score

1

Best

—

 

Take card 0 (1) from the left. Left sum 1

Next

Take card 1 (2) from the left. Left sum 3

Cards

k

3

Watch how we start with the first k cards, then progressively swap a left card for a right card to find the optimal combination.