LeetCode 1423, Medium. Topics: Array, Sliding Window, Prefix Sum. View on LeetCode.
Generate this problem as a practice environment: tested reference solution, 22 parametrized pytest cases, and a playground notebook:
Problem
There are several cards <strong>arranged in a row</strong>, and each card has an associated number of points. The points are given in the integer array <code>cardPoints</code>.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly <code>k</code> cards.
Your score is the sum of the points of the cards you have taken.
Given the integer array <code>cardPoints</code> and the integer <code>k</code>, return the <em>maximum score</em> you can obtain.
Examples
Explanation: After the first step, your score will always be 1. However, choosing the rightmost card first will maximize your total score. The optimal strategy is to take the three cards on the right, giving a final score of 1 + 6 + 5 = 12.
Explanation: Regardless of which two cards you take, your score will always be 4.
Explanation: You have to take all the cards. Your score is the sum of points of all cards.
Constraints
1 <= cardPoints.length <= 10^5
1 <= cardPoints[i] <= 10^4
1 <= k <= cardPoints.length
Solution
Reference implementation from solution.py on GitHub, full suite in test_solution.py:
Complexity
NeetCode All. Last modified on September 7, 2026