Workspace Maximum Sum Subarray Of Size K
0d
DSA Problem Sheet

Maximum Sum Window

Among all consecutive windows containing exactly target items, return the largest sum.

EXECUTION LAB

Among all consecutive windows containing exactly target items, return the largest sum.

Input and constraints
  • Target is a window size from 1 through the array length.
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
total = 0
right = 0
while (right < target):
total = (total + values[right])
right = (right + 1)
best = total
left = 0
while (right < len(values)):
total = ((total - values[left]) + values[right])
best = max(best, total)
left = (left + 1)
right = (right + 1)
return best

Visualizer

Step 1 of 6
04right
1-1
23
35
4-2

Build the first window

Build the first window.

Variable watch

right 0total 0target 2

Step explanation

Build the first window.

comparisons 1reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(n) time · O(1) space

Worked explanation

A camera frame pans across a row; only the two edges change.

Guided solution

When moving one place, remove the outgoing value and add the incoming one.

O(n) time · O(1) auxiliary space

Examples

Worked example · {"values":[4,-1,3,5,-2],"target":2} ⇒ 8

Edge case 1 · {"values":[-5,-2],"target":1} ⇒ -2

Edge case 2 · {"values":[2],"target":1} ⇒ 2

Progressive hints

Hint 1A camera frame pans across a row; only the two edges change.
Hint 2When moving one place, remove the outgoing value and add the incoming one.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

A best sum of zero fails when every valid window has negative sum.

Interview follow-up

Could the same update maintain a window minimum?