如何在java中找到具有最大序列和的子数组?

时间:2016-09-19 22:09:56

标签: java

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

2 个答案:

答案 0 :(得分:1)

只记得当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 );

答案 1 :(得分:0)

如果您有总和,则意味着在您的代码中的某个时刻,您的代码知道它对该点的最大价值。为什么不为每个和保存字符串中的序列,并在每次有最大总和时用下一个序列替换字符串,最后你将得到其值和值已经在你的maxSum变量中的序列。

相关问题