Skip to content

Instantly share code, notes, and snippets.

@ujjawalsidhpura
Created August 25, 2021 15:31
Show Gist options
  • Save ujjawalsidhpura/538003842fb389fc8c7d472394d8b100 to your computer and use it in GitHub Desktop.
Save ujjawalsidhpura/538003842fb389fc8c7d472394d8b100 to your computer and use it in GitHub Desktop.
Max sum subarray
Have the function MaxSubarray(arr) take the array of numbers stored in arr and determine
the largest sum that can be formed by any contiguous subarray in the array.
For example, if arr is [-2, 5, -1, 7, -3] then your program should return 11 because the sum is formed by the subarray
[5, -1, 7]. Adding any element before or after this subarray would make the sum smaller.
function MaxSubArray(arr) {
let currentSum = arr[0];
let maxSum = arr[0];
for (let i = 1; i < arr.length; i++) {
currentSum = Math.max(currentSum + arr[i], arr[i])
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment