Complete the code to initialize the variable that stores the maximum sum found so far.
let maxSoFar = [1];We start with the smallest possible number so any sum will be larger.
Complete the code to update the current sum by adding the current array element.
currentSum = currentSum [1] nums[i];We add the current element to the running sum to consider subarrays ending at this index.
Fix the error in the condition that resets currentSum when it becomes negative.
if (currentSum [1] 0) { currentSum = 0; }
If currentSum is less than zero, we reset it to zero to start a new subarray.
Fill both blanks to update maxSoFar if currentSum is greater.
if (currentSum [1] maxSoFar) { maxSoFar = [2]; }
We update maxSoFar only if currentSum is larger, so maxSoFar becomes currentSum.
Fill all three blanks to complete the Kadane's algorithm function.
function maxSubArray(nums) {
let maxSoFar = [1];
let currentSum = 0;
for (let i = 0; i < nums.length; i++) {
currentSum = currentSum [2] nums[i];
if (currentSum [3] 0) currentSum = 0;
if (currentSum > maxSoFar) maxSoFar = currentSum;
}
return maxSoFar;
}This completes the Kadane's algorithm by initializing maxSoFar, adding current element, and resetting currentSum if negative.
