算法题之——连续子数组最大和

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013293125/article/details/77680159

Java算法题之——连续子数组最大和

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

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

代码:

//时间复杂度为O(n)
public static void maxSum(int a[]){
        int max = a[0];
        int sum = 0;
        for(int i=0;i<a.length;i++){
            sum+=a[i];
            if(sum>max){
                max = sum;
            }else if(sum<0){
                sum = 0;
            }
        }
        System.out.println(max);
    }

猜你喜欢

转载自blog.csdn.net/u013293125/article/details/77680159