mediumArraySliding WindowSliding Window

Maximum Points You Can Obtain from Cards

mediumTime: O(k)Space: O(1)

Signals to notice

pick cards from either endmaximize sum of k cardscomplement sliding window

Brute force first

Try all combinations of taking from left and right. Each pick is a binary choice. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

The key insight

Instead of picking k cards from ends, think of it as leaving n-k contiguous cards in the middle. Find the minimum sum window of size n-k. Answer = totalSum - minWindowSum. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

What must stay true

Taking k from the ends is equivalent to NOT taking n-k from the middle. Minimizing the middle window maximizes the taken cards. This converts a hard end-picking problem to a simple sliding window. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Easy way to go wrong

Not seeing the complement — trying to directly model 'take from left or right' is complex. The window-on-middle approach is much simpler. Most mistakes here are not about syntax; they come from losing track of what your state, pointer, or structure is supposed to mean.

Sliding Window Pattern