题目
https://leetcode-cn.com/problems/maximum-subarray/
思路
- dp
- 贪心
code
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubArray = function (nums) {
// return greedy(nums);
return dp_f(nums);
};
const greedy = function (nums) {
let max = -Infinity;
let cur = 0;
let len = nums.length;
for (let i = 0; i < len; i++) {
cur += nums[i];
if (cur > max) max = cur;
if (cur < 0) cur = 0;
}
return max;
}
const dp_f = function (nums) {
let dp = 0;
let res = -Infinity;
for (let i = 0; i < nums.length; i++) {
dp = Math.max(nums[i] + dp, nums[i]);
res = Math.max(res, dp);
}
return res;
}