Skip to content

Instantly share code, notes, and snippets.

@javi-aire
Last active April 4, 2020 05:50
Show Gist options
  • Save javi-aire/77130c76c645ef999c88036580402c0d to your computer and use it in GitHub Desktop.
Save javi-aire/77130c76c645ef999c88036580402c0d to your computer and use it in GitHub Desktop.
Problem 3/30 of LeetCode 30-day challenge (main solution from article, added comments for understanding)
/**
* Given at least one number
* find the total from a
* contiguous set of numbers
*/
let maxSubArray = function(nums) {
// setting to -infinity handles
// negative comparisons
let max = -Infinity;
temp = -Infinity;
// array with one element case
if(nums.length === 1) {
return nums[0];
}
for(let i = 0; i < nums.length; i++) {
// check for negative nums
// resets to 0 if temp is negative
temp = Math.max(0, temp);
// add one num at a time
temp += nums[i];
// set max
max = Math.max(max, temp);
}
return max;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment