Leetcode #1423: Maximum Points You Can Obtain from Cards
In this guide, we solve Leetcode #1423 Maximum Points You Can Obtain from Cards in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
There are several cards arranged in a row, and each card has an associated number of points. The points are given in the integer array cardPoints.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Array, Prefix Sum, Sliding Window
Intuition
We are looking for a contiguous region that satisfies a constraint, which is a classic sliding-window signal.
Expanding and shrinking the window lets us maintain validity without restarting the scan.
Approach
Grow the window with a right pointer, and shrink from the left only when the constraint is violated.
Track the best window as you go to keep the solution linear.
Steps:
- Expand the right end of the window.
- While invalid, move the left end to restore constraints.
- Update the best window found.
Example
Input: cardPoints = [1,2,3,4,5,6,1], k = 3
Output: 12
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.
Python Solution
class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
ans = s = sum(cardPoints[-k:])
for i, x in enumerate(cardPoints[:k]):
s += x - cardPoints[-k + i]
ans = max(ans, s)
return ans
Complexity
The time complexity is , where is the integer given in the problem. The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.