Skip to problem
←

Maximum Points You Can Obtain from Cards

Medium 0 attempts

A row of cards is laid out in front of you, each worth some number of points. On each turn you can grab a card only from the front or the back of the row, and you must grab exactly k cards in total. Your score is the sum of the points on the cards you've collected. Return the highest score achievable.

You may switch ends between turns, but cannot take an interior card until it becomes an end card. Taking fewer than k cards is not allowed.

For [9,1,1,9] with k = 2, take one card from each end to score 18. For [1,100,2] with k = 1, the answer is 2: the middle card is not available.

Function contract

Implement maxScore(cardPoints, k). Receive positive card values in their original row order and the exact number of cards to take.

Output: Return the maximum sum obtainable by removing exactly k cards from the current front or back.

Example 1

Input
cardPoints = [1,2,3,4,5,6,1]
k = 3
Output
12

Example 2

Input
cardPoints = [1,2,3]
k = 3
Output
6
Constraints
  • 1 <= cardPoints.length <= 10^5
  • 1 <= cardPoints[i] <= 10^4
  • 1 <= k <= cardPoints.length

Taking k cards from the ends is equivalent to leaving a contiguous subarray of size n - k in the middle. To maximize the points from the k cards, minimize the sum of the middle n - k cards using a sliding window.

javascript
function maxScore(cardPoints, k) {
  const n = cardPoints.length;
  const windowSize = n - k;
  let windowSum = 0;

  for (let i = 0; i < windowSize; i++) {
    windowSum += cardPoints[i];
  }

  let minWindowSum = windowSum;
  const totalSum = cardPoints.reduce((a, b) => a + b, 0);

  for (let i = windowSize; i < n; i++) {
    windowSum += cardPoints[i] - cardPoints[i - windowSize];
    minWindowSum = Math.min(minWindowSum, windowSum);
  }

  return totalSum - minWindowSum;
}

Time: O(n) Space: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript