JavaScript 中子数组的最大连续和
javascriptweb developmentfront end technologyobject oriented programming更新于 2024/2/21 22:36:17
我们需要编写一个 JavaScript 函数,该函数接受一个包含正整数和负整数的数组。由于该数组还包含负元素,因此连续元素的总和可能是负数或正数。
我们的函数应该从总和最大的数组中选择一个连续元素数组。最后,该函数应该返回该数组。
例如 −
如果输入数组是 −
const arr = [-2, -3, 4, -1, -2, 1, 5, -3];
那么最大可能的总和是 7,输出子数组应该是 −
const output = [4, -1, -2, 1, 5];
示例
以下是代码 -
const arr = [-2, -3, 4, -1, -2, 1, 5, -3];
const maximumSubarray = (arr = []) => {
let max = -Infinity;
let currentSum = 0;
let maxStartIndex = 0;
let maxEndIndex = arr.length - 1;
let currentStartIndex = 0;
arr.forEach((currentNumber, currentIndex) => {
currentSum += currentNumber;
if (max < currentSum) {
max = currentSum;
maxStartIndex = currentStartIndex;
maxEndIndex = currentIndex;
}
if (currentSum < 0) {
currentSum = 0;
currentStartIndex = currentIndex + 1;
}
});
return arr.slice(maxStartIndex, maxEndIndex + 1);
};
console.log(maximumSubarray(arr));
输出
以下是控制台上的输出 −
[ 4, -1, -2, 1, 5 ]
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

