Niuke.com brush question|Maximum sum of consecutive subarrays

Topic source: Niuke.com

programming connection

Topic description

HZ occasionally takes some professional questions to fool those non-computer majors. After the meeting of the test group today, he spoke again: in the ancient one-dimensional pattern recognition, it is often necessary to calculate the maximum sum of continuous sub-vectors. When the vectors are all positive numbers, the problem is easy to solve. But if the vector contains negative numbers, should it contain some negative number and expect the positive number next to it to make up for it? For example: {6,-3,-2,7,-15,1,2,2}, the maximum sum of consecutive sub-vectors is 8 (starting from the 0th and ending at the 3rd). Will you be fooled by him? (the length of the subvector is at least 1)

Topic Analysis:

The topic is very classic. What else can I say about the examples in the data structure book?
There are many solutions, first come with a violent solution, the algorithm complexity is 0 (n^2)

Code:
Traverse all consecutive subarrays and save the largest one for output.
Each time there is a new starting point, the sum needs to be set to 0.

class Solution {
public:
    int FindGreatestSumOfSubArray(vector<int> array) {
        int ThisSum,i,j = 0;
        int MaxSum =  0x80000000;
        for(int i = 0;i<array.size();i++)
        {
            ThisSum = 0;
            for(int j = i;j<array.size();j++)
            {
                ThisSum  += array[j];
                if(ThisSum > MaxSum) 
                {
                    MaxSum = ThisSum;
                }
            }
        }      
        return MaxSum;           
    }
};

Using the idea of ​​dynamic programming, keep recording the current value and the next value for comparison

/*
算法时间复杂度O(n)
用total记录累计值,maxSum记录和最大
基于思想:对于一个数A,若是A的左边累计数非负,那么加上A能使得值不小于A,认为累计值对
          整体和是有贡献的。如果前几项累计值负数,则认为有害于总和,total记录当前值。
此时 若和大于maxSum 则用maxSum记录下来
*/
public class Solution {
    public int FindGreatestSumOfSubArray(int[] array) {
        if(array.length==0)
            return 0;
        else{
            int total=array[0],maxSum=array[0];
            for(int i=1;i<array.length;i++){
                if(total>=0)
                    total+=array[i];
                else
                    total=array[i];
                if(total>maxSum)
                    maxSum=total;
            }
            return maxSum;
        }

    }
}

Optimized code:

链接:https://www.nowcoder.com/questionTerminal/459bd355da1549fa8a49e350bf3df484
来源:牛客网

int FindGreatestSumOfSubArray(vector<int> array) {
        if(array.empty()) return 0;
        int sum = array[0], tempsum = array[0]; //注意初始值 不能设为0 防止只有负数
        for(int i = 1; i < array.size(); i++) //从1开始 因为0的情况在初始化时完成了
        {
            tempsum = (tempsum < 0) ? array[i] : tempsum + array[i];
            sum = (tempsum > sum) ? tempsum : sum;
        }
        return sum;
    }

Another way of writing:

链接:https://www.nowcoder.com/questionTerminal/459bd355da1549fa8a49e350bf3df484
来源:牛客网

class Solution {
public:
    int FindGreatestSumOfSubArray(vector<int> a) {
      if(!a.size()) return 0;
        int mx = 0x80000000;
        for(int i = 0, s = 0; i < int(a.size()); ++i){
            s = max(s + a[i], a[i]);  //因为加上a[i]还小于a[i]的话就说明前面的s小于0
            mx = max(mx, s);
        }
        return mx;
    }
};

A kind of weird idea;
first traverse the array, sum and save in turn.
The subarray sum is the sum of the end position minus the sum of the start position, and the
largest subarray sum is recorded.
code show as below:

class Solution {
public:
    int FindGreatestSumOfSubArray(vector<int> array) {
        vector<int>sum(array);
        int ret = -0x3f3f3f3f;
        for(int i = 1;i<array.size();sum[i] = sum[i-1] + array[i],i++);
        for(int len = 1;len <= array.size();len++)
        {
            for(int i = 0;i+len-1<array.size();i++)
            {                
                ret = max(ret,sum[len+i-1] - (i?sum[i-1]:0));
            }
        }
        return ret;  
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325602320&siteId=291194637