首页 > 其他 > 详细

连续子数组的最大和

时间:2014-09-11 09:32:31      阅读:187      评论:0      收藏:0      [点我收藏+]

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

public class Main {
    public static int getMaxSum(int[] array) throws Exception{
        
        if (array == null && array.length == 0) {
            throw new Exception() ;
        }
        
        int maxSum = array[0];
        int tempSum = maxSum;
        for (int i = 1; i < array.length; i++) {
            if (tempSum < 0) {
                tempSum = array[i];
            } else {
                tempSum += array[i];
            }
            
            if (tempSum >= maxSum) {
                maxSum = tempSum;
            }
        }
        return maxSum;
    }
    
    public static void main(String[] args) {
        int[] array = {-1, -2, -3, -10, -4, -5, -2, -5};
        try {
            System.out.println(getMaxSum(array));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 

连续子数组的最大和

原文:http://www.cnblogs.com/wanghui390/p/3965708.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!