Problem Statement
Explain fixed and variable sliding window with an example problem.
Explanation
A fixed window keeps a constant size and slides forward, updating a running state. For example, maximum sum of k-size subarray: add the new right item and remove the left item as the window moves. This gives linear time with constant extra space.
A variable window grows and shrinks based on a rule. For longest substring without repeats, expand right while all characters are unique. When a repeat appears, shrink left until valid again. This balances correctness and speed in a single pass.
Code Solution
SolutionRead Only
def max_sum_k(nums, k):
s = sum(nums[:k]); best = s
for i in range(k, len(nums)):
s += nums[i] - nums[i-k]
best = max(best, s)
return best