Leetcode题解之 —— 最大子序和

思路


动态规划

  • Math.max更新最大值
  • 更新currentSum, 即当前序列和

题解


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function(nums) {
let [maxSum, currentSum] = [-Number.MAX_VALUE, 0];

for (const value of nums) {
currentSum += value;

maxSum = Math.max(currentSum, maxSum);
currentSum = currentSum < 0 ? 0 : currentSum;
}

return maxSum;
};