algorighm/top-interview-leetcode150/kadane/53最大子数组之和.js

25 lines
555 B
JavaScript
Raw Permalink 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}
*/
const maxSubArray = function (nums) {
return f1(nums);
};
/*
定义dp[i]表示以nums[i]结尾的最大子数组和那么dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]),要么是前面最大的子数组
加上自己,要么是自己本身
*/
function f1(nums) {
let max = nums[0];
const dp = new Array(nums.length).fill(0);
dp[0] = nums[0];
for (let i = 1; i < nums.length; i++) {
dp[i] = Math.max(dp[i - 1] + nums[i], nums[i]);
max = Math.max(max, dp[i]);
}
return max;
}