Skip to content

Instantly share code, notes, and snippets.

@wataruoguchi
Created July 31, 2019 03:00
Show Gist options
  • Save wataruoguchi/adaf2ac7381e43a9f0fac61e31f36c45 to your computer and use it in GitHub Desktop.
Save wataruoguchi/adaf2ac7381e43a9f0fac61e31f36c45 to your computer and use it in GitHub Desktop.
// https://www.geeksforgeeks.org/largest-sum-contiguous-subarray/
// https://practice.geeksforgeeks.org/problems/kadanes-algorithm/0
function maxSubArraySum(arr, len) {
let maxSoFar = Math.min(...arr);
let maxEndingHere = 0;
let idx;
for (idx = 0; idx < len; idx++) {
maxEndingHere = maxEndingHere + arr[idx];
if (maxSoFar < maxEndingHere) {
maxSoFar = maxEndingHere;
}
if (maxEndingHere < 0) {
maxEndingHere = 0;
}
}
return maxSoFar;
}
const nums1 = [1,2,3,-2,5];
const result1 = maxSubArraySum(nums1, nums1.length);
console.log(result1, result1 === 9);
const nums2 = [-1,-2,-3,-4];
const result2 = maxSubArraySum(nums2, nums2.length);
console.log(result2, result2 === -1);
const example = [-2,-3,4,-1,-2,1,5,-3];
const resultEx = maxSubArraySum(example, example.length);
console.log(resultEx, resultEx === 7);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment