Maximum Subarray
Difficulty: Medium
Problem
Given an integer array nums, find the subarray with the largest sum, and return its sum.
Example
Input: nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6
Explanation: The subarray [4, -1, 2, 1] has the largest sum 6.
Brute-force approach
Check every possible subarray by trying all start and end positions, calculating each sum.
Steps
- Try every starting position
- Try every ending position after start
- Calculate sum of each subarray
- Track the maximum sum found
Time complexity: O(n²) · Space complexity: O(1)
Trade-offs
- Checks many overlapping subarrays redundantly
- Recalculates sums that share common elements
- Quadratic time is slow for large arrays
Optimal approach
Key insight: At each index, the max subarray ending here is either: just this element alone, or this element plus the max subarray ending at the previous index.
Kadane's Algorithm: at each position, decide whether to extend the current subarray or start fresh from the current element.
Steps
- Track current sum and max sum
- At each element: decide extend or restart
- Update maxSum if currentSum is larger
- Return maxSum
Time complexity: O(n) · Space complexity: O(1)