The sword refers to the maximum sum of consecutive subarrays of offer

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)
The basic idea

Traverse the array, use the max variable to record the maximum accumulated sum of the sub-arrays that appear during the traversal process, and use the sum variable to record the accumulated sum. When the sum variable is less than 0, reset it to 0 (because the maximum accumulated sum is to be found, so if If the accumulated sum is already negative, it will no longer be counted in the accumulated sum, discard the negative value, and start accumulating from 0), and then start accumulating again. After the traversal is over, return the maximum value max found.


AC Code (Java)
public class Solution {
    public int FindGreatestSumOfSubArray(int[] array) {
        if(array==null || array.length==0){
            return 0;
        }
        int sum=0, max=Integer.MIN_VALUE;
        for(int i=0; i<array.length; i++){
            sum+=array[i];
            if(sum>max){
                max=sum;
            }
            if(sum<0){
                sum=0;
            }
        }
        return max;
    }

}

Guess you like

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