我想编写一个函数来确定数组中任何连续子数组可以形成的最大和。
Input: [-2, 5, -1, 7, -3]
Output: 11 //because of subarray [5, -1, 7]
Input: [1, 2, -10, 20, 1]
Output: 21 //because of [20, 1]
我的尝试
function Max (array) {
let result = Math.max(...array); //in case that there is only one pos. number or all neg.
for (let i = 0; i<array.length; i++) {
for (let j=0; j<array.length; j++) {
if (array.reduce((array[i], array[j]) => array[i], array[j]))
> result)
{result = array.reduce((array[i], array[j]) => array[i], array[j]));
}
}
array.shift[array[i]];
array.pop[array[i]];
}
return result
}
我的想法如下:
Input [1, 2, 3, 4, -5]
--->
----->
-------->
-------------> //check each of the 4 sums against the result
[2, 3, 4, -5, 1]
--->
----->
-------->
-------------> //check each of the 4 sums against the result
[3, 4, -5, 1, 2]
--->
----->
-------->
-------------> //check each of the 4 sums against the result
基本思想应该是正确的,但我无法在代码中正确实现它。感谢所有阅读本文甚至帮助初学者的人!