Workspace Maximum Subarray
0d
DSA Problem Sheet

Maximum Subarray

Return the largest sum of a nonempty contiguous segment.

EXECUTION LAB

Return the largest sum of a nonempty contiguous segment.

Input and constraints
  • Supply at least one value.
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
ending = values[0]
best = ending
i = 1
while (i < len(values)):
ending = max(values[i], (ending + values[i]))
best = max(best, ending)
i = (i + 1)
return best

Visualizer

Step 1 of 5
0-3
14i
2-1
35
4-8

Inspect the current state

Choose between a fresh start and extending the segment.

Variable watch

i 1ending -3best -3

Step explanation

Choose between a fresh start and extending the segment.

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

Worked explanation

Carry yesterday’s savings forward only when they improve today’s balance.

Guided solution

The best segment ending here either starts here or extends the previous best ending.

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

Examples

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

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

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

Progressive hints

Hint 1Carry yesterday’s savings forward only when they improve today’s balance.
Hint 2The best segment ending here either starts here or extends the previous best ending.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

Initializing the answer to zero incorrectly allows an empty segment on all-negative input.

Interview follow-up

How would you recover both endpoints?