https://leetcode.com/problems/maximum-subarray/description/
输入测试用例:
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算法解决所有这些测试用例,还是需要以其他方式实现?
谢谢!
答案 0 :(得分:0)
var maxSubArray = function(nums) {
let maxn = -Number.MAX_VALUE;
let sum = 0;
nums.forEach(function(item, index, array) {
sum += item;
if (sum > maxn)
maxn = sum;
if (sum < 0)
sum = 0;
});
return maxn;
};
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
&#13;
答案 1 :(得分:0)
最大总和连续子数组。
这是我的解决方案,用于在一维数字数组中找到总和最大的连续子数组的和。
我编写此代码时没有遵循任何算法。
function lrgSumContiArr(arr) {
function getSum(startIndex, endIdex){
return arr.slice(startIndex, endIdex).reduce((acc, cur) => acc + cur);
}
const lrgSumArrOfSubArr = arr.map((item, index) =>{
let largeSum = Number.NEGATIVE_INFINITY;
for(let i=index; i<arr.length; i++) {
let subArrSum = getSum(index,i+1);
if( subArrSum > largeSum) {
largeSum = subArrSum;
}
}
return largeSum;
});
/* const lrgSumOfSubArr = lrgSumArrOfSubArr.reduce((acc, cur) => {
if (acc > cur){
return acc;
} else {
return cur;
}
});
return lrgSumOfSubArr; */
return Math.max.apply(null,lrgSumArrOfSubArr);
}
lrgSumContiArr([-2,-3,4,-1,-2,1,5,2]);
答案 2 :(得分:0)
function maxSubarray(a) {
var l=a.length;
if (!l) {
return;
}
var ps, ms;
ps=ms=a[0];
for(var i=1; i<l; i++) {
ps=Math.max(a[i],ps+a[i]);
ms=Math.max(ms,ps);
}
return ms;
}
答案 3 :(得分:0)
刚看到, 它将找到最大子数组的总和
public class MaxSubArray{
static void sumM(int a[], int n){
int s1 = Integer.MAX_VALUE;
int k = Integer.MAX_VALUE;
int sum = 0;
int s2 = 0;
for(int i=0;i<n;i++){
if(a[i]<s1){
if(a[i]<0){
k = Math.min(a[i],s1);
}
}
if(a[i]>k){
sum+=a[i];
}
if(a[i]<k){
if(a[i]<0){
continue;
}
s2+=a[i];
}
}
if(sum>s2){
System.out.println(sum);
}
else{
System.out.println(s2);
}
}
public static void main(String[] args){
int a[] = {1,2,3,-7,4,5};
int n = a.length;
sumM(a,n);
}
}