Leetcode 714. The best time to buy and sell stocks includes handling fees

Leetcode 714. The best time to buy and sell stocks includes handling fees

Question stem

Given an integer array prices, the i-th element represents the stock price on the i-th day; the non-negative integer fee represents the transaction cost of stocks.
You can complete transactions indefinitely, but you need to pay a handling fee for each transaction. If you have already bought a stock, you can no longer buy stocks before you sell it.
Returns the maximum profit obtained.
Note: A transaction here refers to the entire process of buying, holding and selling stocks. You only need to pay a handling fee for each transaction.

Example 1:
Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
Explanation: The maximum profit that can be achieved:
buy here prices[0] = 1
sell here Out prices[3] = 8
Buy here prices[4] = 4
Sell ​​here prices[5] = 9
Total profit: ((8-1)-2) + ((9-4)-2 ) = 8.

注意:
0 < prices.length <= 50000.
0 < prices[i] < 50000.
0 <= fee < 50000.

answer

The simple and rude dp, the idea is basically the same as 122. The best time to buy and sell stocks, the only thing to consider is the issue of handling fees.
According to the description of the title, the handling fee is charged once for one transaction, not once for each transaction. Therefore, the initial value of dp[0][1] and the handling fee when transferred to dp[i][0] are affected. deal with

class Solution {
    
    
public:
    int maxProfit(vector<int>& prices, int fee) {
    
    
        int n = prices.size();
        vector<vector<int> > dp(n,vector<int>(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] - fee);
            dp[i][1] = max(dp[i-1][0] - prices[i],dp[i-1][1]);
        }
        return dp[n-1][0];
    }
};
/*
    dp[i][j]记录当前持有的最大金额,负数时为总亏损状态.j为状态位,0表示当前未持股票,1表示当前持有股票
    考虑初值:
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
    考虑状态转移方程:
        dp[i][0] = dp[i-1][0];
        dp[i][0] = dp[i-1][1] + prices[i] - fee;
        dp[i][1] = dp[i-1][0] - prices[i];
        dp[i][1] = dp[i-1][1];
    考虑结果:
        dp[prices.size()-1][0];
    由题意,手续费的收取是一次买卖收一次的,所以只在转移到未持股状态时才有可能-fee
*/

In fact, the state transfer is constantly updating the state of the two transactions, so you can save the array space and use two variables to store the holdings (because the result is the final state)

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

Wonderful

Guess you like

Origin blog.csdn.net/weixin_43662405/article/details/111313618