Arrays & Sliding Window (Medium) / 121. Maximum Subarray Sum (Kadane's Algorithm)
121. Maximum Subarray Sum (Kadane's Algorithm)
MediumGiven an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Example 2:
Input: nums = [1]
Output: 1
- 1
Understand the Goal: We want to find the maximum sum of a contiguous subarray.
- 2
Kadane's Algorithm:
- 3
Iterate through the array.
- 4
Maintain a
current_sum. Only add the next element tocurrent_sumifcurrent_sumis positive. Ifcurrent_sumis negative, it's better to start a new subarray from the current element. - 5
Wait, the logic is:
current_sum = max(num, current_sum + num). This decides whether to extend the existing subarray or start a new one. - 6
Keep track of the
max_sumfound so far. - 7
Edge Cases: Array with all negative numbers (should return the single largest element, which is the least negative one).