DSA Tracker

Problem

Medium

Maximum Subarray

A medium Arrays interview guide. Task statement, worked examples, intuition, and step-by-step solutions.

Topic
Arrays
Sheets
3
Core for
26 roles

The problem

Given an integer array, find the contiguous subarray containing at least one element that produces the greatest sum.

Example 1

Input
nums = [3,-4,2,-1,5,-3,1,-2]
Output
6
Why
The run [2,-1,5] gives 2 + (-1) + 5 = 6; stretching it left picks up -4 and stretching it right picks up -3, both of which lower the total.

Example 2

Input
nums = [1]
Output
1
Why
The single element forms the only subarray and yields a sum of 1.

Example 3

Input
nums = [6,-2,3,-1,4]
Output
10
Why
Taking the whole array gives 6 - 2 + 3 - 1 + 4 = 10; each negative is outweighed by the positives around it.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4

How to think about it

Updated 2026-09-29

A running prefix sum that drops below zero is an active liability to whatever comes next. Any future subarray would strictly benefit from throwing that negative prefix away and starting fresh from the current number. Walking left to right and making this binary choice at each step boils the problem down to tracking a single running accumulator.

Approaches, worst first

  1. Exhaustive subarray scanning

    time O(n^2) · space O(1)

    Compute the sum of every possible subarray (i, j) using two nested loops. Directly evaluates every candidate slice in the array, but repeatedly sums overlapping spans and consumes quadratic runtime.

  2. Divide and conquer boundary merge

    time O(n log n) · space O(log n)

    Split the array in half and recursively find the best subarray in the left half, the right half, and crossing the center. Combines boundary answers efficiently, but adds recursive stack overhead and extra code complexity compared to a linear scan.

  3. Kadane running accumulatorWrite this one

    time O(n) · space O(1)

    Maintain currentSum and maxSum initialized to nums[0]. For each subsequent element, set currentSum to max(num, currentSum + num) and update maxSum. Discarding negative running sums ensures optimal greedy continuation in a single pass.

Where people lose marks · 3
  • Initializing the maximum sum to 0 instead of nums[0] or negative infinity, which causes arrays of entirely negative numbers to incorrectly report 0.
  • Resetting currentSum to 0 before updating maxSum on negative numbers, which ignores individual negative values that should be valid answers.
  • Assuming the maximum subarray must contain positive numbers, failing on arrays like [-5, -2, -8] where the answer is -2.

Full solution

Kadane's running accumulator: a linear scan that discards any prefix once it turns negative, since no future subarray benefits from carrying it forward. This is the answer an interview expects over the quadratic or divide-and-conquer alternatives.

Python
def max_subarray(nums: list[int]) -> int:
    current_sum = max_sum = nums[0]
    for num in nums[1:]:
        # Drop the running prefix once it becomes a liability; start fresh at num.
        current_sum = max(num, current_sum + num)
        max_sum = max(max_sum, current_sum)
    return max_sum
JavaScript
function maxSubArray(nums) {
  let currentSum = nums[0];
  let maxSum = nums[0];
  for (let i = 1; i < nums.length; i++) {
    // Drop the running prefix once it becomes a liability; start fresh at num.
    currentSum = Math.max(nums[i], currentSum + nums[i]);
    maxSum = Math.max(maxSum, currentSum);
  }
  return maxSum;
}
Try it in the editor

The theory behind it

Arrays — the ground this problem stands on. All Arrays problems

What Arrays is

An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.

When to reach for it

Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.

How the pattern works

Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.

More Arrays problems

Track in your role's order

Pick your target role and all 370 problems resequence to what that interview actually asks.

Start free

Problem set and role mapping as of .