Jack Li's Blog

0714.Best Time to Buy and Sell Stock with Transaction Fee

2-DP #

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int n = prices.size();
        vector<vector<int>> dp(n, vector<int>(2));

        for(int i = 0; i < n; i++) {
            dp[i][0] = -prices[0];
        }

        for(int i = 1; i < n; i++) {
            // buy score
            // i-1 day no buy and buy in i day
            // i-1 already buy
            dp[i][0] = max(dp[i-1][1] - prices[i], dp[i-1][0]);
            // sell score
            // i-1 buy and sell at i day
            // i-1 no buy
            dp[i][1] = max(dp[i-1][0] + prices[i] - fee, dp[i-1][1]);
        }

        return dp[n-1][1];
    }
};

1-DP #

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int n = prices.size();
        vector<int> dp(2);
        dp[0] = -prices[0];

        for(int i = 1; i < prices.size(); i++) {
            dp[0] = max(dp[1] - prices[i], dp[0]);
            dp[1] = max(dp[0] + prices[i] - fee, dp[1]);
        }

        return dp[1];
    }
};