LeetCode #53: Maximum Subarray — your first Medium problem! This introduces Kadane's Algorithm, one of the most elegant algorithms ever.
Given an array of integers, find the contiguous subarray with the largest sum.
Example:[-2, 1, -3, 4, -1, 2, 1, -5, 4]
The subarray [4, -1, 2, 1] has the largest sum = 6
Kadane's Algorithm — The Idea:
As you scan left to right, keep a running sum. At each element, ask: 'Should I continue the current subarray, or start fresh from here?'
💭 Your turn! Take what you learned above and write the code yourself. Struggling is part of learning! 🧠
Walk-through with [-2, 1, -3, 4, -1, 2, 1, -5, 4]:
Complexity: Time O(n), Space O(1). Beautiful!
def maxSubArray(nums):
current_sum = nums[0]
max_sum = nums[0]
for i in range(1, len(nums)):
# Either extend current subarray or start new one
current_sum = max(nums[i], current_sum + nums[i])
max_sum = max(max_sum, current_sum)
return max_sum
maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])
6
maxSubArray([1])
1
maxSubArray([5, 4, -1, 7, 8])
23