Maximum Subarray - Problem
You are given an integer array nums. Your task is to find the contiguous subarray (containing at least one number) that has the largest sum and return that sum.
A subarray is a contiguous part of an array. For example, in the array [1, 2, 3], the subarrays are: [1], [2], [3], [1, 2], [2, 3], and [1, 2, 3].
Goal: Find the subarray with maximum sum efficiently.
Input: An integer array nums
Output: An integer representing the maximum sum of any contiguous subarray
Input & Output
example_1.py โ Basic Case
$
Input:
[-2,1,-3,4,-1,2,1,-5,4]
โบ
Output:
6
๐ก Note:
The subarray [4,-1,2,1] has the largest sum of 6. This demonstrates how we can include negative numbers if they're surrounded by larger positive numbers.
example_2.py โ Single Element
$
Input:
[1]
โบ
Output:
1
๐ก Note:
When there's only one element, it forms the maximum subarray by itself.
example_3.py โ All Negative Numbers
$
Input:
[-3,-2,-1,-4]
โบ
Output:
-1
๐ก Note:
When all numbers are negative, we choose the least negative number as our maximum subarray. Here -1 is the largest among all negative numbers.
Visualization
Tap to expand
Understanding the Visualization
1
Track Running Profit
Keep adding daily profits to your running total
2
Remember Best Period
Always remember the best consecutive period seen so far
3
Cut Losses
If your running total goes negative, start fresh from the next day
4
Optimal Strategy
This greedy approach guarantees finding the maximum profit period
Key Takeaway
๐ฏ Key Insight: If your current profit streak becomes negative, it's always better to start fresh rather than carry the loss forward. This greedy decision leads to the optimal solution!
Time & Space Complexity
Time Complexity
O(nยฒ)
Two nested loops: outer loop runs n times, inner loop runs up to n times
โ Quadratic Growth
Space Complexity
O(1)
Only using a few variables to track sums and indices
โ Linear Space
Constraints
- 1 โค nums.length โค 105
- -104 โค nums[i] โค 104
- The array contains at least one element
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code