The sword refers to Offer 42. The maximum sum of consecutive sub-arrays (C++) dynamic programming

Enter an integer array. One or more consecutive integers in the array form a sub-array. Find the maximum value of the sum of all sub-arrays.
The required time complexity is O(n).

Example 1:

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

prompt:

1 <= arr.length <= 10^5
-100 <= arr[i] <= 100
Note: This question is the same as Question 53 of the main site: https://leetcode-cn.com/problems/maximum-subarray/

Problem-solving ideas:

Insert picture description here

Insert picture description here
Insert picture description here

class Solution {
    
    
public:
    int maxSubArray(vector<int>& nums) {
    
    
        int res=nums[0];
        int n=nums.size();
        for(int i=1;i<n;i++)
		{
    
    
			nums[i] += nums[i - 1]>0?nums[i - 1]:0;
			res = res>nums[i]?res:nums[i];
			//nums[i] += max(nums[i - 1], 0);
			//res = max(res, nums[i]);
		}     
        return res;
    }
};

Insert picture description here

Author: jyd
link: https: //leetcode-cn.com/problems/lian-xu-zi-shu-zu-de-zui-da-he-lcof/solution/mian-shi-ti-42-lian-xu -zi-shu-zu-de-zui-da-he-do-2/
Source: LeetCode (LeetCode)
copyright belongs to the author. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Guess you like

Origin blog.csdn.net/qq_30457077/article/details/114851315