[剑指 offer] JT30---Maximum sum of consecutive sub-arrays (dynamic programming [the most detailed illustration of the entire network])

The topic is as follows

Insert picture description here

Dynamic programming analysis

What is dynamic programming?
It is the optimization theory, we want to get the best, then the answer is not only the current best, but also depends on whether the previous state is the best.
How to use dynamic programming?
The most important thing to use dynamic programming is to findState transition equation
Take this question as an
example. Let’s use the dp array to record the 8 numbers in the sample.
The meaning is: The sum of the largest sub-array containing the i-th number (i is at least 0) is the number itself

dp[0] dp[1] dp[2] dp[3] dp[4] dp[5] dp[6] dp[7]
1 -2 3 10 -4 7 2 -5

The most important thing is to find the state transition equation. It
is actually very easy to find. It is to add the largest sub-array in the front and compare it with yourself. If the previous one becomes larger, just update the dp array.
Students, let's run this dp array together!
dp[0]=1;
dp[1]=dp[1]+dp[0]>dp[1]?dp[1]+dp[0]:dp[1]=dp[0]+dp[1 ]=1-2=-1;
dp[2]=dp[2]+dp[1]>dp[2]?dp[2]+dp[1]:dp[2]=dp[2]=3 ; I
won’t write judgments below, it is directly equal to it, and everyone should understand it.Typing tired TT
dp[3]=3+10=13;
dp[4]=13-4=9;
dp[5]=9+7=16;
dp[6]=16+2=18;
dp[7]=18-5=13;
The dp array after dynamic programming is as follows:

dp[0] dp[1] dp[2] dp[3] dp[4] dp[5] dp[6] dp[7]
1 -1 3 13 9 16 18 13

At a glance, the maximum sum is the maximum value inside, which is 18

Did you suddenly feel that dynamic programming is very simple, and you understand it all at once!

code show as below

class Solution {
    
    
public:
    int FindGreatestSumOfSubArray(vector<int> array) {
    
    
        int currCrest=array[0],crest=array[0];
        for(int i=1;i<array.size();i++){
    
    
            currCrest=max(currCrest+array[i],array[i]);
            crest=max(currCrest,crest);
        }
        return crest;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_42136832/article/details/114867405