Skip to content

Instantly share code, notes, and snippets.

@sAVItar02
Created October 26, 2024 18:18
Show Gist options
  • Save sAVItar02/0b33f2ee9505ec880fc884cdc8676c77 to your computer and use it in GitHub Desktop.
Save sAVItar02/0b33f2ee9505ec880fc884cdc8676c77 to your computer and use it in GitHub Desktop.
Maximum Subarray
/**
* @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