#1423
Medium Algorithms Maximum points you can obtain from cards
Array Sliding Window Prefix Sum
57.3% acceptance
Feb 25, 2026
7050
318
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.
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 the integer array cardPoints and the integer k, return the maximum score you can obtain.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn max_score(card_points: Vec<i32>, k: i32) -> i32 {
let n = card_points.len();
let k = k as usize;
let total: i32 = card_points.iter().sum();
let window = n - k;
// minimize the sum of the middle window of size 'window'
let mut win_sum: i32 = card_points[..window].iter().sum();
let mut min_win = win_sum;
for i in window..n {
win_sum += card_points[i] - card_points[i - window];
min_win = min_win.min(win_sum);
}
total - min_win
}
}