Problem 302015 · medium · Level 03 Linear Management & Searching

Cards from the Ends

sliding window · fixed-size window · complement

A row of cards has point values cards. You draw exactly k cards, each time taking either the leftmost or the rightmost remaining card, and you may mix the two freely. Return the maximum total you can collect.

Examples

Input:  cards = [1, 2, 3, 4, 5, 6, 1], k = 3
Output: 12
Explanation: take the right card three times: 1 + 6 + 5 = 12.

Input:  cards = [2, 2, 2], k = 2
Output: 4

Input:  cards = [9, 7, 7, 9, 7, 7, 9], k = 7
Output: 55

Constraints

  • 1 <= k <= len(cards) <= 10**5
  • -10**4 <= cards[i] <= 10**4
  • Target complexity: O(n) time; enumerating every left/right split and re-summing is too slow for the largest tests.

Goals

  • Reframe picking from both ends as leaving a contiguous middle
  • Minimise a fixed-size window sum
Starting Python…