码迷,mamicode.com
首页 > 编程语言 > 详细

连续子数组的最大和

时间:2018-07-02 11:01:00      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:组成   gets   turn   很多   sum   复杂度   []   +=   system   

题目:输入一个整型数组,数组里有正数也有负数。数组中一个活连续的多个整数组成一个子数组。求所有子数组的和的最大值。要求事件复杂度为O(n)。

思路:看到这道题,很多人都能想到最直观的方法,即枚举出数组的所有数组并求出它们的和。一个长度为n的数组,总共有n(n+1)/2个子数组。计算出所有子数组的和,最快也需要O(n2)的时间。通常最直观的方法不会是最优的解法。

public class subMax{
    public int getSubMax(int[] array){
        if(array == null || array.length == 0) return 0;
        int max = array[0];
        int sum = 0;
        for(int i=0;i<array.length;i++){
            sum += array[i];
            if(sum>max){
                max = sum;
            }
            else if(sum<0){
                sum = 0;
            }
        }
        return max;
    }
    public static void main(String[] args){
        int[] array = {1,-2,3,10,-4,7,2,-5};
        subMax  s = new subMax();
        int result = s.getSubMax(array);
        System.out.println(result);
    }
}

 

连续子数组的最大和

标签:组成   gets   turn   很多   sum   复杂度   []   +=   system   

原文地址:https://www.cnblogs.com/yingpu/p/9252115.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!