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 = [4, 9, 1, 1, 2, 8, 3], k = 3
Output: 16
Explanation: take two cards from the left and one from the right: 4 + 9 + 3 = 16.

Input:  cards = [3, 7, 3], k = 2
Output: 10

Input:  cards = [6, 1, 8, 2], k = 4
Output: 17

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…