经典笔试面试题-数组中最大的子数组之和

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

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

package HuaWei;

public class Main2 {

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        int[] a = { 1, -2, 3, 10, -4, 7, 2, -5 };
        int max = MaxSum(a);
        System.out.println(max);
    }

    public static int MaxSum(int[] a) {
        int out = 0;
        int temp = 0;
        for (int i = 0; i < a.length; i++) {
            temp = temp + a[i];
            if (temp > out)
                out = temp;
            if (temp < 0)
                temp= 0;
        }
        return out;
    }

}

测试用例:
1,-2,3,5,-3,-2 输出结果:8

0,-2,3,5,-1,2 输出结果:9

-9,-2,-3,-5,-3,-8 输出结果:-2

猜你喜欢

转载自blog.csdn.net/qq_27028821/article/details/52652269
今日推荐