Show problems as
Classic problem #1423MediumArraySliding WindowPrefix Sum

Maximum Points You Can Obtain from Cards

Real-world version: Forklift Picks from the Crate Row
Tracked in this browser only
Read Maximum Points You Can Obtain from Cards on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstSliding Window · Arrays, animated step by step

Crates stand in a single line along a loading aisle. cardPoints[i] is the mass of the crate at position i, reading from the front of the line to the back.

A forklift makes exactly k pickups. Each pickup removes either the crate currently at the front of the line or the crate currently at the back of the line; the crate behind or in front of it then becomes the new end. Nothing may be taken from the middle.

Return the largest total mass the forklift can carry away.

Examples

Example 1

Input
cardPoints = [5, 4, 9, 1], k = 2
Output
10

Take the back crate of mass 1, then the crate of mass 9 that is now at the back. Both pickups came from an end and there were exactly two of them, giving 10.

Example 2

Input
cardPoints = [6, 6, 6], k = 2
Output
12

Every crate weighs 6, so any two pickups carry away 12.

Example 3

Input
cardPoints = [7, 4, 8], k = 3
Output
19

There are three crates and three pickups, so the line empties and the whole 7 + 4 + 8 = 19 leaves on the forklift.

Constraints

  • 1 <= cardPoints.length <= 10^5
  • 1 <= cardPoints[i] <= 10^4
  • 1 <= k <= cardPoints.length

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def max_score(cardPoints: list[int], k: int) -> int:
Java
public int maxScore(int[] cardPoints, int k)