The best time to buy and sell stocks in Leikou 2021.1.9

Problem:
Given an array, its i-th element is the price of a given stock on the i-th day.
Design an algorithm to calculate the maximum profit you can get. You can complete up to two transactions.
Note: You cannot participate in multiple transactions at the same time (you must sell the previous stocks before buying again).
Example 1:
Input: prices = [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on the 4th day (stock price = 0), and on the 6th day (stock Price = 3) when you sell, the exchange can make a profit = 3-0 = 3.
Then, buy on the 7th day (stock price = 1), and sell on the 8th day (stock price = 4). The exchange can make a profit = 4-1 = 3.
Example 2:
Input: prices = [1,2,3,4,5]
Output: 4
Explanation: Buy on the 1st day (stock price = 1), and on the 5th day (stock price = 5) Sell, this exchange can make a profit = 5-1 = 4.
Note that you cannot buy stocks one after another on the first and second days and then sell them later.
Because this is involved in multiple transactions at the same time, you must sell the previous stocks before buying again.
Example 3:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is completed, so the maximum profit is 0.
Example 4:
Input: prices = [1]
Output: 0

Idea:
dp algorithm, considering the five operations per day (no operation, first buying, first selling, second buying, second selling), the corresponding profit expression is enough.
Code:

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

    }
};

Guess you like

Origin blog.csdn.net/weixin_45780132/article/details/112388641