欢迎来到码农小陈的博客

最大子序列

请找出在一串有正有负的整数序列中,最大的子序列的总和
Input
第一行为序列的个数N
之後有N行序列,每行都有10个数,序列中的每个元素可能为正可能为负
Output
请输出每个序列中可以找出的最大的连续元素(子序列)的和
例如范例中的最後几个元素{19,-12,20,5}相加为32,是整个序列中所能找到的最大的子序列的和
Sample input
1
13 -11 -3 9 -19 -5 19 -12 20 5
Sample output
32


 

答案:

 

public static int maxSubSum(List<Integer> a){
        int maxSum = 0;
        int thisSum = 0;
        for(int i=0; i<a.size(); i++){
            thisSum += a.get(i);
            if(thisSum > maxSum)
                maxSum = thisSum;
            else if(thisSum<0)
                 thisSum = 0;
        }  
         return maxSum;
    }

 

posted on 2020-08-03 03:22  码农小陈  阅读(204)  评论(0编辑  收藏  举报

导航