Python coding

Most points from the ends of a row

Cards lie face up in a row, and cards[i] is the number of points on card i. You take exactly k cards, one at a time, and each must come from the left end or the right end of what is left of the row. Return the most points you can collect.

Points may be negative or zero; 0 <= k <= len(cards). Aim for O(k) time and O(1) extra space: adding up both ends again for every split is O(k²).

Besides the tests, one large input (16,000 cards, k = 8,000) with a ~150 ms limit (scaled to your device's speed): brute force won't pass.

  • max_points([1,2,3,4,5,6,1], 3) → 12
  • max_points([2,2,2], 2) → 4
  • max_points([9,7,7,9,7,7,9], 7) → 55
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

The order of the picks doesn't matter, only how many come from the left: i from the left and k - i from the right, for some i from 0 to k.

Hint 2

Start with all k from the left. Each step gives back the innermost left card and takes one more from the right: a window of k cards sliding around the end, O(1) per step.

Solution and why it works
pythonO(k) · O(1)
def max_points(cards: list[int], k: int) -> int:
    total = best = sum(cards[:k])        # all k picks from the left
    for i in range(1, k + 1):
        total += cards[-i] - cards[k - i]   # one more from the right, one fewer from the left
        best = max(best, total)
    return best

Any pick is i cards from the left plus k - i from the right, so there are only k + 1 candidates, and neighbors differ by one card in and one out: a fixed window of k cards wrapping around the end, O(1) per slide, O(k) in all. Equivalently, the cards left behind form one contiguous block of n - k. Taking the bigger end each time is the trap: on [5, 100, 1, 1, 6] with k = 2 it takes 6 and 5, missing 105.

Related lab: Sliding window, step by step