<分区>
** 最大和子数组问题在于找到最大和
of a contiguous subsequence in an array or list of integers: maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]) // should be 6: [4, -1, 2, 1] Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.
Empty list is considered to have zero greatest sum. Note that the
空列表或数组也是有效的子列表/子数组。**
var maxSequence = function(arr) {
// ...
let max = 0;
const sorted = arr.sort((a, b) => {
return a - b;
});
if (arr.length == 0) {
return 0;
} else if (sorted[sorted.length - 1] >= 0 && sorted[0] >= 0) {
let max = 0;
for (let i = 0; i < sorted.length; i++) {
max += sorted[i];
}
return max;
} else if (sorted[0] < 0 && sorted[sorted.length - 1] < 0) {
console.log(0);
} else {
let halfLength = Math.floor(arr.length / 2);
let pivot = 0;
let sequence = 0;
let next = 1;
while (pivot <= arr.length - 1) {
if (arr[next] <= halfLength) {
sequence += arr[next];
next += 1;
} else {
sequence = 0;
halfLength += 1;
pivot += 1;
next = pivot + 1;
}
if (pivot == arr.length - 2) {
sequence += arr[next];
next += 1;
break;
}
if (sequence >= max) {
max = sequence;
}
}
console.log("the answer", max);
}
};
maxSequence([-2, 1, -3, 4, -1, 2, 1, -5, 4]); //, 6)
**The code return 12 instead of 6 any solution i have been trying for an hour now **