剑指Offer.42——连续子数组的最大和

题目链接:https://leetcode-cn.com/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof/

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

输入: nums = [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

遍历到每个数,就把在当前位置时最大连续数值求出,然后再不断更新最大值

class Solution {
    public int maxSubArray(int[] nums) {
        int maxInt = nums[0];
        for (int i = 1; i < nums.length; i++){
            nums[i] += Math.max(nums[i - 1], 0);
            maxInt = Math.max(maxInt, nums[i]);
        }
        return maxInt;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43207025/article/details/107931668