Maximum Subarray – Solution & Complexity
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.
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.
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.
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.
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.