SDE & MLE Prep

1423. Maximum Points You Can Obtain from Cards

Problem

Cards lie in a row with cardPoints[i] points. Take exactly k cards, each from either the left or the right end of the row. Return the maximum total points.

Example: cardPoints = [1,2,3,4,5,6,1], k = 3 → 12 (take 6, 5, 1 from the right)

Constraints: n ≤ 10⁵.

Taking k cards from the ends leaves a contiguous window of n − k cards in the middle. Minimize that window's sum; answer = total − min window.

Complexity: O(n).

class Solution:
    def maxScore(self, cardPoints: List[int], k: int) -> int:
        n, w = len(cardPoints), len(cardPoints) - k
        s = best = sum(cardPoints[:w])
        for i in range(w, n):
            s += cardPoints[i] - cardPoints[i - w]
            best = min(best, s)
        return sum(cardPoints) - best