42-连续子数组的最大和

2020-05-06  本文已影响0人  一方乌鸦

输入一个整型数组,数组里有正数也有负数。数组中的一个或连续多个整数组成一个子数组。求所有子数组的和的最大值。

要求时间复杂度为O(n)。

class Solution {
    public int maxSubArray(int[] nums) {
        int lastMax = nums[0];
        int max = lastMax;
        for (int i = 1; i < nums.length; i++) {
            lastMax = Math.max(nums[i], lastMax + nums[i]);
            max = Math.max(max, lastMax);
        }
        return max;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读