algorighm/dynamic-programming/subsequence/53最大子数组和.js

28 lines
583 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) {
};
/*
定义dp[i]为从nums[i]开始的和最大的子数组那么动态转移方程为dp[i] = dp[i+1] + nums[i] (dp[i+1] > 0)
*/
function f1(nums) {
const dp = Array(nums.length + 1).fill(0); // dp[i]表示从i位置开始的和最大子数组
let result = -Infinity;
for (let i = nums.length - 1; i >= 0; i--) {
if (dp[i + 1] > 0) {
dp[i] = nums[i] + dp[i + 1];
} else {
dp[i] = nums[i];
}
result = Math.max(result, dp[i]);
}
return result;
}