Space
Open
From Fieldwork
Scales
Archive
Initial State: Imagine you picked all k cards from the start of the array. We calculate that sum.
The Slide: We iterate k times. In every iteration, we "put back" the right-most card of our left selection and "pick up" the next available card from the right end of the array.
class Solution:
def maxScore(self, cardPoints: List[int], k: int) -> int:
# 1. Start by taking all k cards from the left side.
left_sum = sum(cardPoints[:k])
right_sum = 0
max_points = left_sum
n = len(cardPoints)
# 2. Slide the window: give one up from the left, take one from the right.
for i in range(k):
# Remove the last card we took from the left
left_sum -= cardPoints[k - 1 - i]
# Add a card from the end of the array (right side)
right_sum += cardPoints[n - 1 - i]
# Update maximum found so far
max_points = max(max_points, left_sum + right_sum)
return max_pointsPractice bench
A private scratchpad for this reading. Nothing is sent or scored.
What is still unclear, or what would change the explanation?
Saved on this device · one draft per mode