PROBLEM 61 OF 75 · CODE STUDIO

Maximum Subarray

Given a non-empty integer array, return the largest sum of any non-empty contiguous subarray. The chosen segment may contain one element or the entire array.

Know the exact contract

  • The local studio receives one or more finite safe integers; generated test sums remain within JavaScript’s exact integer range.
  • The result must come from a contiguous, non-empty segment. Do not return zero merely because all values are negative.
EXAMPLE 1numbers = [-2, 1, -3, 4, -1, 2, 1, -5, 4]→ 6

The contiguous segment [4, -1, 2, 1] sums to 6.

EXAMPLE 2numbers = [-5, -2, -8]→ -2

The single value -2 is better than every other non-empty segment.

EXAMPLE 3numbers = [4, -1, 2]→ 5

Keeping the small negative bridge connects 4 and 2 into a better segment.

Earn the faster approach

SIMPLE APPROACH

Try every start index, extend an end index while maintaining its running sum, and keep the largest value. This inspects O(n²) contiguous segments and uses O(1) extra space.

IMPROVED APPROACH

Scan left to right. Let ending be the best non-empty segment that must end at the current position. Either start anew with the current value or extend the best segment ending one position earlier. Update a global best after each choice.

Why it works

After index i, ending is the maximum sum among non-empty subarrays ending exactly at i. Every such subarray is either the single value at i or extends a subarray ending at i−1, so max(value, previousEnding + value) is complete.

Cost

The scan visits every value once and stores only ending and best, so it takes O(n) time and O(1) extra space. The nested-start baseline takes O(n²) time.

A tempting mistake

For [-5, -2, -8], initializing best to zero incorrectly chooses an empty segment. The problem requires a non-empty answer, so initialize from the first value.

FOLLOW THE ACTUAL STATE

Watch the best ending sum

Each frame shows the current value, the previous ending sum, whether the scan restarts or extends, and the best result found anywhere so far.

STEP 1 / 9

Index 0, value -2. Best ending here: -2; best anywhere: -2.

The first value is the only non-empty subarray ending here.
Result: 6
RECALL BEFORE RECOGNITION

Can you rebuild the reasoning?

Without looking back at the explanation, name the signal, the state you keep, one safe transition, the cost, and a case that breaks a tempting mistake. This writing is private and not automatically graded.

Review the lesson →
INDEPENDENT SOLVE

Now write the code.

Write solve(data). data.numbers is a non-empty integer array. Return the maximum sum of a contiguous non-empty segment. Checks include mixed, all-negative, single-value, and fresh arrays.

Opening the code studio…

PROVE IT AGAIN TOMORROW

A fresh solve is the test.

Loading your saved attempts…

This lesson uses original explanations and examples. For additional practice, see the related LeetCode challenge.