Maximum Subarray - 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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
💡 Note: The subarray [4,-1,2,1] has the largest sum = 6
Example 2 — Single Element
$ Input: nums = [1]
Output: 1
💡 Note: Array has only one element, so maximum subarray sum is 1
Example 3 — All Negative
$ Input: nums = [-2,-1]
Output: -1
💡 Note: The subarray [-1] has the largest sum = -1

Constraints

  • 1 ≤ nums.length ≤ 105
  • -104 ≤ nums[i] ≤ 104

Visualization

Tap to expand
Maximum Subarray ProblemInput Array:-21-34-121-54Maximum Subarray:[4, -1, 2, 1]Sum = 4 + (-1) + 2 + 1 = 6Maximum Sum: 6
Understanding the Visualization
1
Input Array
Array with positive and negative integers
2
Find Best Subarray
Identify contiguous elements with maximum sum
3
Return Sum
Output the maximum subarray sum
Key Takeaway
🎯 Key Insight: Reset running sum to zero whenever it becomes negative, as negative prefixes never help maximize the total sum
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
125.0K Views
Very High Frequency
~15 min Avg. Time
2.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen