用友2016成都校园招聘笔试题

有幸获得一份用友2016成都校园招聘的笔试题,就拿来做了一下。

题目:输入一个整形数组,数组里有正数也有负数。数组中连续的一个或多个整数组成一个子数组,每一个子数组都有一个和。求所有子数组的和的最大值。要求时间复杂度为O(n)。

例如输入的数组为1,-2,3,10,-4,7,2,-5,那么该数组中连续的最大的子数组为3,10,-4,7,2,因此输出为该子数组的和18。

代码如下:

public class Sum {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
         int[] a={1,-2,3,10,-4,7,2,-5};
         int max=FindMax(a);
         System.out.print(max);
    }    
    static int FindMax(int[] a){
        int max=0;
        int tmp=0;
        for(int i=0; i<a.length;i++){
            if(a[i]>0 || tmp>Math.abs(a[i])){
                tmp+=a[i];
                if(tmp>max){
                    max=tmp;
                }
            }else{
                tmp=0;
            }
        }
        return max;
    }
}
posted @ 2015-10-31 15:36  好哥在路上  阅读(162)  评论(0编辑  收藏  举报