Maximum Subarray – Solution & Complexity
Quick practice for Maximum Subarray: 3 reasoning beats, no typing
Watch: Maximum Subarray with Kadane's algorithm
At each number, decide whether to extend the current run or start fresh. If the running sum has gone negative, it can only drag the next number down, so drop it. Track the best sum seen. O(n) time, O(1) space.
Solution Walkthrough
Step 1: Understand the Problem
- We need the largest possible sum from one contiguous subarray.
- The subarray must contain at least one number.
- Negative numbers matter because the best answer could be a single negative element.
Step 2: Start with a Brute Force Idea
- Try every possible start and end index.
- Compute each subarray sum and keep the largest.
- This is correct but inefficient because there are O(n²) subarrays.
Step 3: Key Insight: Keep the Best Ending Here
- At each number, decide whether to extend the previous subarray or start fresh.
- If the previous running sum is harmful, starting at the current number is better.
- Track both the best sum ending at the current index and the best sum seen overall.
Step 4: Apply Kadane's Algorithm
- Initialize both values with the first element.
- For every next number, update
currentto the better of starting new or extending. - Then update
bestwith the larger value.
Step 5: Final Solution and Complexity
- Kadane's algorithm scans the array once.
- Time complexity is O(n).
- Space complexity is O(1) because only two running values are stored.