Maximum Subarray medium
Problem Statement
Find the contiguous subarray within an array (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
Example 3:
Input: nums = [5,4,-1,7,8] Output: 23
Steps
The most efficient approach to solve this problem is Kadane's Algorithm. The algorithm iterates through the array, keeping track of the current maximum sum and the overall maximum sum.
-
Initialization: Initialize two variables:
maxSoFar
(to store the overall maximum sum) andmaxEndingHere
(to store the maximum sum ending at the current position). Both are initialized to the first element of the array. -
Iteration: Iterate through the array from the second element.
-
Update
maxEndingHere
: For each element, updatemaxEndingHere
as follows:- If
maxEndingHere
is positive, add the current element to it. - If
maxEndingHere
is negative or zero, it means the current element starts a new potentially larger sum, so setmaxEndingHere
to the current element.
- If
-
Update
maxSoFar
: After updatingmaxEndingHere
, compare it withmaxSoFar
. IfmaxEndingHere
is greater thanmaxSoFar
, updatemaxSoFar
tomaxEndingHere
. -
Return
maxSoFar
: After iterating through the entire array,maxSoFar
will contain the maximum subarray sum.
Explanation
Kadane's algorithm cleverly avoids the need to check all possible subarrays. By only keeping track of the maximum sum ending at the current position, it efficiently identifies the overall maximum sum. If the current maximum sum (maxEndingHere
) becomes negative, it means that including the previous elements is detrimental to the overall sum; therefore, a new subarray starting from the current element is considered.
Code
function maxSubArray(nums: number[]): number {
let maxSoFar = nums[0];
let maxEndingHere = nums[0];
for (let i = 1; i < nums.length; i++) {
maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
};
Complexity
- Time Complexity: O(n), where n is the length of the input array. The algorithm iterates through the array once.
- Space Complexity: O(1). The algorithm uses a constant amount of extra space to store the variables
maxSoFar
andmaxEndingHere
.