Leek-- 122. The Best Time to Buy and Sell Stocks II

1. Topic:

Topic Link: 122. The Best Time to Buy and Sell Stocks II - LeetCode

2. Problem-solving steps

The following is the process of solving this problem with the idea of ​​​​dynamic programming . I believe that everyone can understand and master this classic dynamic programming problem.

3. Reference code:

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n=prices.size();
        vector<int> f(n);
        auto g=f;
        f[0]=-prices[0];
        g[0]=0;
        for(int i=1;i<n;i++)
        {
            f[i]=max(f[i-1],g[i-1]-prices[i]);
            g[i]=max(g[i-1],f[i-1]+prices[i]);
        }
        return g[n-1];
    }
};

The above is the whole process of analyzing this topic with the idea of ​​dynamic programming , have you learned it? If the above solutions are helpful to you, then please be careful and pay attention to it. We will continue to update the classic questions of dynamic programming in the future . See you in the next issue! ! ! ! ! ! ! ! !

Guess you like

Origin blog.csdn.net/weixin_70056514/article/details/131865159