js-practice/src/array/maximum-subarray.js
2020-05-03 19:11:29 +08:00

12 lines
317 B
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @param {number[]} nums
* @return {number}
*/
export const maxSubArray = function (nums) {
let max = nums[0]
let tmp = 0
nums.forEach(n => { max = Math.max(tmp > 0 ? tmp += n : tmp = n, max) })
// 如果当前指针所指元素之前的和小于0则丢弃当前元素之前的数列
return max
}