"Sword Finger Offer"-30, the largest sum of consecutive sub-arrays

1. Knowledge points of this question

Dynamic programming

2. Title description

Enter an integer array. There are positive and negative numbers in the 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).

3. Problem solving ideas

This problem can be regarded as a multi-stage decision-making problem to find the optimal solution, so it can be solved with typical dynamic programming ideas.

Use res[i] to represent the maximum sum of the sub-array ending with the i-th element, then the following recurrence formula:

res[i]=max(res[i-1]+data[i], data[i])

The meaning of this formula is: when the sum of all numbers in the sub-array ending with the i-1th number is less than 0, add this negative number to the i-th number, and the resulting sum is smaller than the i-th number itself , So in this case res[i] is the i-th number itself. Conversely, if the sum of all numbers in the sub-array ending with the i-1th digit is greater than 0, the sum of all numbers in the sub-array ending with the i-th digit will be obtained by accumulating with the i-th digit.

4. Code

public class Solution {
    
    
    public int FindGreatestSumOfSubArray(int[] array) {
    
    
        int max = array[0];
        for (int i = 1; i < array.length; i++) {
    
    
            if (array[i - 1] > 0) {
    
    
                array[i] += array[i - 1];
            }
            max = Math.max(max, array[i]);
        }
        return max;
    }
}

Guess you like

Origin blog.csdn.net/bm1998/article/details/113902456