如果数组是{-1 3 -1 9 4 -4}。我希望输出为
“总和为 15,数组为 {3 -1 9 4}。”
我有求和的代码,但是如何获取这个子数组?
这是求和的代码
int maxSum = 0, thisSum = 0;
for( int j = 0; j < a.length; j++ ){
thisSum += a[ j ];
if( thisSum > maxSum ){
maxSum = thisSum;
}
else if( thisSum < 0 )
thisSum = 0;
}
System.out.println( maxSum );
最佳答案
只要记住,当 from 和 to 为 0 并且 sum 为零时,这可能意味着您有一个空子数组(假设所有子数组都是负数)。
int []a = {-1, 3, -1, 9, 4, -4};
int from=0, to=0;
int maxSum = 0, thisSum = 0, thisFrom = 0 ;
for( int j = 0; j < a.length; j++ ){
if (thisSum == 0){ thisFrom = j ; }
thisSum += a[ j ];
if( thisSum > maxSum ){
from = thisFrom;
to = j;
maxSum = thisSum;
}
else if( thisSum < 0 )
thisSum = 0;
}
System.out.println(Arrays.toString(Arrays.copyOfRange(a, from, to+1)));
System.out.println( maxSum );
关于java - java中如何找到序列和最大的子数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39582864/