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
Maximum Subarray: Trading Profit AnalogyTrading Days Timeline-21-34-121-54Best Trading PeriodTotal Profit: 6Kadane's Algorithm Strategy๐Ÿ’ฐ Rule 1: Keep adding daily profits to your running total๐Ÿ“ˆ Rule 2: Always remember the best consecutive period so farโœ‚๏ธ Rule 3: If running total goes negative, start fresh tomorrow๐ŸŽฏ Result: This greedy approach finds the optimal trading periodTime Complexity: O(n) - Single pass | Space: O(1) - Only two variables"Sometimes the best strategy is knowing when to cut your losses and start fresh!"
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

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

Only using a few variables to track sums and indices

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 105
  • -104 โ‰ค nums[i] โ‰ค 104
  • The array contains at least one element
Asked in
Google 65 Amazon 58 Meta 42 Microsoft 38 Apple 25
94.2K Views
Very High Frequency
~15 min Avg. Time
2.8K 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