JavaScript 中连续子数组的最大和
我们需要编写一个 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 ]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP