#53

Maximum Subarray

MediumKadane / DPHas vizArrayDynamic Programming
Related studio

Problem

Given an integer array nums, find the subarray with the largest sum, and return its sum.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]

Output: 6

The subarray [4,-1,2,1] has the largest sum 6.

Example 2

Input: nums = [1]

Output: 1

Single element.

Example 3

Input: nums = [5,4,-1,7,8]

Output: 23

The whole array is optimal.

Constraints

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

Explanation

Maximum Subarray is a Medium interview problem tagged [Array, Dynamic Programming]. The winning approach is typically **Kadane / DP**.

Intuition

Local ending-best combines into global maximum subarray in O(n).

Approach

Track the best subarray ending at i; either extend previous or start fresh at i.

  1. cur = max(x, cur+x).
  2. best = max(best, cur).
  3. Handle all-negative arrays carefully.

Solution

Curated solution in C#, Python, Java, JavaScript, and C++ — switch languages with the tabs.

Exact solutionKadane / DP

Edge cases

  • •Empty or single-element input
  • •Duplicates and ties
  • •Maximum constraints / overflow
  • •Disconnected or unreachable states (for graphs)

Complexity

Time: O(n)

Space: O(n)

Before coding, restate the problem, name the pattern (Kadane / DP), and write the invariant or DP state in one sentence.

Learn the topic

Got it?

Mark #53 Maximum Subarray as understood when the pattern clicks.