Created
August 25, 2021 15:31
-
-
Save ujjawalsidhpura/538003842fb389fc8c7d472394d8b100 to your computer and use it in GitHub Desktop.
Max sum subarray
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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