Maximum Subarray

MediumKadane’s Algorithm · DP🧩 Kadane's Running BestLeetCode #53 ↗Updated

Problem

Given an integer array nums (which may contain negatives), pick a non-empty contiguous block of elements whose sum is as large as possible and return that sum.
Input[-2,1,-3,4,-1,2,1,-5,4]Output6 ([4,-1,2,1])
Input[1]Output1
Input[5,4,-1,7,8]Output23

1 ≤ n ≤ 105  ·  -104 ≤ nums[i] ≤ 104  ·  Follow-up: also try divide and conquer.

Try it yourself

Java
class Solution {
    public int maxSubArray(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
The best subarray ending at i either extends the best one ending at i-1 or starts fresh at nums[i] — a negative running sum can only hurt, so drop it.
PatternKadane's Running Best

Instinct Best sum or product of a contiguous subarray in one pass? At each index choose - extend the run ending here or restart - and track the global best.

Memory hack Carry the bag only while it helps - a negative past is dead weight, drop it and restart here.

Open the Kadane's Running Best guide →

Approaches

Brute ForceAll Subarrays, Running Sum

Time O(n2)Space O(1)

Fix each start i and extend j to the right, adding nums[j] to a running sum so each subarray costs O(1). Track the maximum over all O(n2) subarrays.

Java
public int maxSubArray(int[] nums) {
    int maxSum = Integer.MIN_VALUE;
    for (int i = 0; i < nums.length; i++) {
        int currentSum = 0;
        for (int j = i; j < nums.length; j++) {
            currentSum += nums[j]; // sum of nums[i..j]
            maxSum = Math.max(maxSum, currentSum);
        }
    }
    return maxSum;
}

Simple, but ~5·109 steps at n = 105 — TLE.

At a glance

LevelApproachTimeSpace
Brute ForceAll Subarrays, Running SumO(n2)O(1)
BetterDivide and ConquerO(n log n)O(log n)
OptimalKadane’s AlgorithmO(n)O(1)
Common pitfalls
  • Initialising maxSum = 0 — returns 0 for all-negative input like [-3,-1].
  • Resetting cur to 0 before updating best — loses negative answers.
  • Confusing subarray (contiguous) with subsequence (sum of all positives).
Interview tips
  • Frame it as DP: dp[i] = max(nums[i], dp[i-1] + nums[i]), then compress to O(1).
  • Ask whether an empty subarray is allowed (here it is not).
  • Mention D&C for the follow-up and why it is O(n log n).
Pattern
Kadane / best-ending-here DP → optimal contiguous subarray where each element extends or restarts.
My notes saved in this browser