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

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

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

示例1:

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

提示:

  • 1 <= arr.length <= 10^5
  • -100 <= arr[i] <= 100

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

Solution 1

贪心算法
时间复杂度 O(n)

class Solution {
    public int maxSubArray(int[] nums) {
        int total = 0;
        int max = Integer.MIN_VALUE;
        for (int n : nums) {
            total += n;
            if (total > max)
                max = total;
            if (total < 0)
                total = 0;
        }
        return max;
    }
}

Solution 2

cpp

class Solution
{
public:
    int maxSubArray(vector<int> &nums)
    {
        if (nums.size() == 0)
            return 0;
        int maxSum = nums[0], sum = 0;
        for (size_t i = 0; i < nums.size(); i++)
        {
            if (sum < 0)
                sum = 0;
            sum += nums[i];
            if (sum > maxSum)
                maxSum = sum;
        }
        return maxSum;
    }
};