代码拉取完成,页面将自动刷新
/**
* Dynamic Programming solution.
* Complexity: O(n)
*
* @param {Number[]} inputArray
* @return {Number[]}
*/
export default function dpMaximumSubarray(inputArray) {
// We iterate through the inputArray once, using a greedy approach to keep track of the maximum
// sum we've seen so far and the current sum.
//
// The currentSum variable gets reset to 0 every time it drops below 0.
//
// The maxSum variable is set to -Infinity so that if all numbers are negative, the highest
// negative number will constitute the maximum subarray.
let maxSum = -Infinity;
let currentSum = 0;
// We need to keep track of the starting and ending indices that contributed to our maxSum
// so that we can return the actual subarray. From the beginning let's assume that whole array
// is contributing to maxSum.
let maxStartIndex = 0;
let maxEndIndex = inputArray.length - 1;
let currentStartIndex = 0;
inputArray.forEach((currentNumber, currentIndex) => {
currentSum += currentNumber;
// Update maxSum and the corresponding indices if we have found a new max.
if (maxSum < currentSum) {
maxSum = currentSum;
maxStartIndex = currentStartIndex;
maxEndIndex = currentIndex;
}
// Reset currentSum and currentStartIndex if currentSum drops below 0.
if (currentSum < 0) {
currentSum = 0;
currentStartIndex = currentIndex + 1;
}
});
return inputArray.slice(maxStartIndex, maxEndIndex + 1);
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。