#53
Maximum Subarray
MediumArrayDivide and ConquerDynamic ProgrammingDynamic ProgrammingSliding Window
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses Kadane's algorithm, which efficiently finds the maximum subarray sum in a single pass through the array. It keeps track of the current subarray sum and updates the maximum sum found so far.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two variables: max_sum to the first element and current_sum to the first element.
- 2Step 2: Iterate through the array starting from the second element.
- 3Step 3: For each element, update current_sum to be the maximum of the current element or current_sum plus the current element.
- 4Step 4: Update max_sum if current_sum is greater than max_sum.
solution.py6 lines
1def maxSubArray(nums):
2 max_sum = current_sum = nums[0]
3 for num in nums[1:]:
4 current_sum = max(num, current_sum + num)
5 max_sum = max(max_sum, current_sum)
6 return max_sumℹ
Complexity note: The time complexity is O(n) because we only make a single pass through the array. The space complexity is O(1) since we are using a constant amount of space.
- 1Kadane's algorithm is a powerful technique for solving maximum subarray problems efficiently.
- 2Understanding how to maintain a running sum can greatly simplify many problems involving arrays.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.