1 Star 0 Fork 2

原罪/javascript-algorithms

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
dpMaximumSubarray.js 1.44 KB
一键复制 编辑 原始数据 按行查看 历史
Oleksii Trekhleb 提交于 2018-09-04 16:39 +08:00 . Minor refactoring of dpMaximumSubarray.
/**
* 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);
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/wzhgitee/javascript-algorithms.git
git@gitee.com:wzhgitee/javascript-algorithms.git
wzhgitee
javascript-algorithms
javascript-algorithms
master

搜索帮助