20220926 - 53. Maximum Subarray 最大子数组和(在线处理)

50 阅读1分钟

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

A subarray is a contiguous part of an array.   Example 1

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Example 2

Input: nums = [1]
Output: 1

Example 3

Input: nums = [5,4,-1,7,8]
Output: 23

  Constraints

  • 1 <= nums.length <= 10e5
  • -10e4 <= nums[i] <= 10e4   Follow up: If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

Solution

第一次尝试:WA

负数用例过不了,因为小于零直接就退出了,输出的是 maxSum 的初始值

int maxSubArray(int* nums, int numsSize){
    int i, thisSum, maxSum;
    thisSum = 0;
    maxSum = 0x80000000;
    for (i = 0; i < numsSize; i++) {
        thisSum += nums[i];
        if (thisSum < 0)
            thisSum = 0;
        else if (thisSum > maxSum)
            maxSum = thisSum;
    }
    return maxSum;
}

第二次尝试:WA

这次先判断 maxSum 再判断大于零,先负数再正数错误,没有更新

int maxSubArray(int* nums, int numsSize){
    int i, thisSum, maxSum;
    thisSum = 0;
    maxSum = 0x80000000;
    for (i = 0; i < numsSize; i++) {
        thisSum += nums[i];
        if (thisSum > maxSum)
            maxSum = thisSum;
        else if (thisSum < 0)
            thisSum = 0;
    }
    return maxSum;
}

第三次尝试:AC

解决方案:把分支去掉,两个 if 就行

int maxSubArray(int* nums, int numsSize){
    int i, thisSum, maxSum;
    thisSum = 0;
    maxSum = 0x80000000;
    for (i = 0; i < numsSize; i++) {
        thisSum += nums[i];
        if (thisSum > maxSum)
            maxSum = thisSum;
        if (thisSum < 0)
            thisSum = 0;
    }
    return maxSum;
}

题目链接:53. 最大子数组和 - 力扣(LeetCode)