Algorithm Learning|Dynamic Programming LeetCode121. The best time to buy and sell stocks, 122. The best time to buy and sell stocks II

1. The best time to buy and sell stocks

Given an array prices, its i-th element prices[i] represents the price of a given stock on the i-th day.
You can only choose to buy the stock on one day and sell it on a different day in the future. Design an algorithm to calculate the maximum profit you can make.
Returns the maximum profit you can make from this trade. If you can't make any profit, return 0.

train of thought

1.dp[i][0] The maximum cash obtained by holding stocks dp[i][1] The maximum cash obtained by not holding stocks
2. Recursive formula: dp[i][0] = max(dp [i - 1][0] ,-prices[i]) dp[i][1] = max(dp[i - 1][1] ,dp[i - 1][0]+ prices[i])
3. Initialization: dp[0][0] = -prices[0] dp[0][1] = 0
4. Traversal order: traverse from front to back

Implementation code

class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
        int len = prices.size();
        if(len == 0) return 0;
        vector<vector<int>> dp(len, vector<int>(2));
        dp[0][0] -= prices[0];
        dp[0][1] = 0;
        for(int i = 1; i < len; i++) {
    
    
            dp[i][0] = max(dp[i - 1][0], -prices[i]);
            dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
        }
        return dp[len - 1][1];
    }
};

2. The best time to buy and sell stocks II

Given an array whose ith element is the price of a given stock on day i. Design an algorithm to calculate the maximum profit you can make. You can complete as many trades as possible (buy and sell a stock multiple times).
Note: You cannot participate in multiple transactions at the same time (you must sell the previous stock before buying again).

train of thought

It can be traded multiple times, so when buying stocks, the cash on hand is not necessarily 0
Recursive formula: dp[i ][0] = max(dp[i - 1][0] , dp[i - 1][1 ] - prices[i]) dp[i][1] = max(dp[i - 1][1] ,dp[i - 1][0]+ prices[i])

Implementation code

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

Guess you like

Origin blog.csdn.net/li26324949/article/details/129963692