42. A continuous subarray and the maximum face questions

Enter an integer array, the array has a positive but also negative. One or more continuous integer array composed of a subarray. Seeking the maximum of all the sub-arrays and.

Required time complexity is O (n).

 

Example 1:

Input: nums = [-2,1, -3,4, -1,2,1, -5,4]
Output: 6
Explanation: continuous subarray [4, -1,2,1], and the most, 6.

 

prompt:

. 1 <= arr.length <= 10. 5 ^
-100 <= ARR [I] <= 100
Note: The same problems present title 53 and the master station: https: //leetcode-cn.com/problems/maximum-subarray/

Problem-solving ideas (dynamic programming):

max: maximum value and the sub-array, the initial value of the first element, sum: the current sub-array and the initial value of the first element.

Through the array, the current value of the sum is determined, and if less than 0, the current element from the beginning again accumulated, and updates the values ​​of max

Code:

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

 

Published 253 original articles · won praise 15 · views 30000 +

Guess you like

Origin blog.csdn.net/junjunjiao0911/article/details/104748692