【发布时间】:2018-03-27 22:36:58
【问题描述】:
https://leetcode.com/problems/maximum-subarray/description/
输入测试用例:
- [-2,1,-3,4,-1,2,1,-5,4]
- [-2, -1]
- [-2, 1]
- [1]
- [1, 2]
function maxSubarray(array) {
var currentMax = array[0];
var max = array[0];
for (var i = 0; i < array.length; i++) {
// Compare 0 and currentMax + array[i]
// IF it is less than 0, it is going to be 0 (Reset)
// it is more than 0, it will be currentMax + next element
currentMax = Math.max(array[i], currentMax + array[i]);
// Compare max or currentMax value, pick up one.
max = Math.max(max, currentMax);
}
// Return max at the end of loop
return max;
}
console.log(maxSubarray([-2,1,-3,4,-1,2,1,-5,4])) // === 6
console.log(maxSubarray([-2, -1])) // === -1
console.log(maxSubarray([-2,1])) // === 1
console.log(maxSubarray([1])) // === 1
console.log(maxSubarray([1, 2])) // === 3
我想通过 Input: [-2, -1] 这个案例,所以我将 var currentMax = 0; 和 var max = 0; 修改为当前代码。
显然,Kadane 的算法需要包含至少一个正数,这样可能无法解决第二种情况。
是否可以通过使用 Kadane 的算法来解决所有这些测试用例,还是我需要以其他方式实现?
谢谢!
【问题讨论】:
标签: javascript algorithm