头图

title: Daily practice (22): the maximum sum of consecutive subarrays

categories:[Swords offer]

tags:[Daily practice]

date: 2022/02/21


Daily practice (22): the maximum sum of consecutive subarrays

Input an integer array, one or more consecutive integers in the array form a subarray. Find the maximum value of the sum of all subarrays.

The required time complexity is O(n).

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]

Output: 6

Explanation: The maximum sum of consecutive subarrays [4,-1,2,1] is 6.

hint:

1 <= arr.length <= 10^5

-100 <= arr[i] <= 100

Source: LeetCode

Link: https://leetcode-cn.com/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof

Method 1: Prefix Sum

Ideas and Algorithms

  1. In the case of negative numbers, sum is the current value each time, and the largest one is compared with maxsum in turn.
  2. Under normal circumstances (positive and negative) cumulative prefix sum, as long as the sum is greater than 0 (there is still value), add it to determine who is greater than the previous maxsum, and take the larger value;
  3. When the current sum becomes smaller to 0 (indicating that the previous negative numbers are offset, and the following numbers are positive or negative, the previous accumulated sum 0 is worthless), then start from the current number again, while ensuring the continuity of the subarrays.
  4. Note that it is not reassignment when a negative number is encountered. In addition, it is necessary to constantly judge whether the current sum is the largest.
int maxSubArray(vector<int>& nums) {
    int maxSum = nums[0];    //默认第一个数为最大值
    int sum = 0;
    for (int i = 0; i < nums.size(); i++) {                
        sum = sum <= 0 ? nums[i] : sum + nums[i];// 当前和不大于0时,说明前面抵消了,从新开始累计和;同样的如果都是负数时,则依次比较哪个最大,赋值给maxSum
        maxSum = sum > maxSum ? sum : maxSum;            // 不停比较更新maxSum
    }
    return maxSum;
}

Method 2: Dynamic Programming (DP Equation)

Ideas and Algorithms

The most primitive dynamic programming

  • Status: dp[i]: The maximum value of the sum ending with the i-th number
  • Transition: If dp[i - 1] < 0, the maximum value of the sum ending with the ith number is the ith number itself
  • If dp[i - 1] > 0, the maximum value of the sum ending with the ith number is the greater of dp[i - 1] and dp[i - 1] + nums[i]
  • Avoid traversing the dp array, and compare the size of res and dp[i] as the return value after each dp update is compared
int maxSubArray(vector<int>& nums) {
    int len = nums.size();
    vector<int> dp(len);
    dp[0] = nums[0];
    int res = nums[0];
    for (int i = 1; i < len; i++) {
        //判断
        if(dp[i - 1] > 0) {
            dp[i] = max(dp[i - 1] + nums[i], nums[i]);
        } else {
            dp[i] = nums[i];
        }
        //三目运算符
        //dp[i] = (dp[i - 1] > 0) ? dp[i] = max(dp[i - 1] + nums[i], nums[i]) : nums[i];
        res = max(res, dp[i]);
    }
    return res;
}

加班猿
50 声望12 粉丝

记录一下生活的点滴,工作上遇到的问题以及学习上的各类笔记