Last active
April 4, 2020 05:50
-
-
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)
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
/** | |
* 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