数组

输入一个整形数组,数组里有正数也有负数。

数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。

求所有子数组的和的最大值。要求时间复杂度为O(n)

思路:从数组的后面排除小于0或者累加小于0的,用max记录被排除的子数组的和的最大值。

public class Test {

 

    public static void main(String[] args) {

        

        int[] a = {1, -2, 3, 10, -4, 7, 2, -5};

        int max = MaxSum(a);

        System.out.println(max);

    }

    

    /***

     * @param a 源数组

     * @return 返回子数组和的最大值

     */

    public static int MaxSum(int[] a){

        int sum = 0;

        int max = 0;

        for(int i=0;i<a.length;i++){

            sum = sum + a[a.length-i-1];

            if(a[a.length-i-1] >= 0){

               if(max < sum){

                  max = sum ;

                }

            }

            if(sum < 0){

                 sum = 0;

             }

        }

        return max;

    }

 

}

原文地址:https://www.cnblogs.com/zaixiachengxuyuan/p/13111058.html