首页 > 编程语言 > 详细

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

时间:2020-06-09 14:41:22      阅读:21      评论:0      收藏:0      [点我收藏+]
public class Item {  
    public static void main(String args[]) {  

       int array[] = {1, 6, 10, -4,8,3, -5};  
       System.out.println(findMax(array));

    }  

    public static int findMax(int array[]){

        if (array.length == 0) {
            return 0;
        }

        int max = array[0];
        int sum = 0;

        for(int i=0; i<array.length; i++){  
           
            if(sum >= 0) { 
                sum += array[i];  
            }
            else{  
                sum = array[i];
            }
            if(sum > max){  
                max = sum;  
            }
        }  
        return max;  
    }
}

 

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

原文:https://www.cnblogs.com/chenaiiu/p/13072185.html

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