Maximum Points You Can Obtain from Cards

There are several cards arranged in a row, and each card has an associated number of points given in the integer array `cardPoints`. In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards. Your score is the sum of the points of the cards you have taken. Given `cardPoints` and `k`, return the maximum score you can obtain.

30:00

Maximum Points You Can Obtain from Cards
medium
Free written solution
Topics
Companies

There are several cards arranged in a row, and each card has an associated number of points given in the integer array cardPoints.

In one step, you can take one card from the beginning or from the end of the row. You have to take exactly k cards.

Your score is the sum of the points of the cards you have taken. Given cardPoints and k, return the maximum score you can obtain.

Example 1:
Input: {"cardPoints":[1,2,3,4,5,6,1],"k":3}
Output: 12
Constraints:
  • 1≤cardPoints.length≤1051 \leq \text{cardPoints.length} \leq 10^5

  • 1≤cardPoints[i]≤1041 \leq \text{cardPoints}[i] \leq 10^4

  • 1≤k≤cardPoints.length1 \leq k \leq \text{cardPoints.length}

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"cardPoints":[1,2,3,4,5,6,1],"k":3}

Start with all 3 cards from the left end: total = 6. Every other hand is a few left cards swapped for right cards.

hand: 3 from the left + 0 from the right

1
2
3
4
5
6
1

0

1

2

3

4

5

6

on table

left

1
2
3

= 6

right

none

k

3

hand total

6

best

6

Variables
VariableValue
k3
total6
best6
DepthFunction Call
Stack empty
0/10