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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code