如果数组是{-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 );