Dynamic programming - the best time to buy and sell stocks with fees

topic

Given an integer array prices, where prices[i] represents the stock price on the ith day; the integer fee represents the transaction fee for the stock.

You can complete an unlimited number of transactions, but you will need to pay a fee for each transaction. If you've already bought a stock, you can't keep buying it until you sell it.

Returns the maximum profit earned.

Note: A transaction here refers to the entire process of buying, holding and selling stocks, and 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: Maximum profit that can be achieved:
buy here prices[0] = 1
sell here prices[ 3] = 8
buy here prices[4] = 4
sell here prices[5] = 9
Total profit: ((8 - 1) - 2) + ((9 - 4) - 2) = 8
Example 2:

Input: prices = [1,3,7,5,10,3], fee = 3
Output: 6

Source: LeetCode
Link: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee

answer

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

    }
};

result

insert image description here

Guess you like

Origin blog.csdn.net/weixin_44901043/article/details/123548935