Created
October 26, 2024 18:18
-
-
Save sAVItar02/0b33f2ee9505ec880fc884cdc8676c77 to your computer and use it in GitHub Desktop.
Maximum Subarray
This file contains 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
/** | |
* @param {number[]} nums | |
* @return {number} | |
*/ | |
var maxSubArray = function(nums) { | |
let sum = 0; | |
let maxSum = nums[0]; | |
for(let i = 0; i < nums.length; i++) { | |
sum += nums[i]; | |
if(sum > maxSum) maxSum = sum; | |
if(sum < 0) sum = 0; | |
} | |
return maxSum; | |
}; | |
// Kadane's Algorithm | |
// Start adding from first element, if at any point the sum goes below 0, then assume the next element is the first element | |
// and repeat till the whole array is traversed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment