Likou selected top interview questions-------the best time to buy and sell stocks

The best time to buy and sell stocks 1

Topic link!

Idea:
There are many ways to solve this problem. Solution one, we can directly use a variable to record the maximum value x on the right side of a certain number, and compare the maximum value x with the number. If it is found that x is greater than the number, then Can produce benefits, and then only need to traverse from the end to the beginning.

Another dynamic programming solution:
Insert picture description here

Code:

class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
        int Max = -1;

        int ans = 0;   //目标量
        for(int i=prices.size()-1;i>=0;--i){
    
    
            if(prices[i]>=Max){
    
    
                Max = max(Max,prices[i]);
                continue;
            }
            
            ans = max(ans,Max-prices[i]);
            
        }
        return ans;
    }
};

//动态规划
class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
        int n = prices.size();
        if (n == 0) return 0; // 边界条件
        int minprice = prices[0];
        vector<int> dp (n, 0);

        for (int i = 1; i < n; i++){
    
    
            minprice = min(minprice, prices[i]);
            dp[i] = max(dp[i - 1], prices[i] - minprice);
        }
        return dp[n - 1];
    }
};

The best time to buy and sell stocks 2

Insert picture description here

Ideas:

  1. Dynamic programming:
    Insert picture description here
  2. Greedy method:
    That is, we can divide the profit. The problem of "greedy" is that for "today's stock price-yesterday's stock price", there are 3 possible results: ① positive number, ② 0, ③ negative number . The decision of the greedy algorithm is: add only positive numbers. In other words, we can subtract each other ( but we don't need to do this when writing the code ), and only sum the positive values ​​of the difference. This thought has to be experienced.
    Insert picture description here
    Here is another wave of handwritten explanations:
    Insert picture description here

Code:

//动态规划
class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
        int n = prices.size();
        int dp[n][2];
        dp[0][0] = 0, dp[0][1] = -prices[0];
        for (int i = 1; i < n; ++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[n - 1][0];
    }
};

//贪心
class Solution {
    
    
public:
    int maxProfit(vector<int>& prices) {
    
    
        int ans = 0;
        for(int i=1;i<prices.size();++i){
    
    
            if(prices[i]>prices[i-1]){
    
    
                ans += (prices[i] - prices[i-1]);
            }
        }
        return ans;
    }
};

Guess you like

Origin blog.csdn.net/weixin_43743711/article/details/114585725