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

same as II, just when selling, there is an additional fee

dp

time: O(n)

space: O(n)

class Solution {
    public int maxProfit(int[] prices, int fee) {
        // fee representing a transaction fee.
        // when selling, there is an additional fee
        // dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i] - fee); // sell
        // dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i]); // buy
        
        if (prices == null || prices.length < 2) return 0;
        int n = prices.length;
        int dp[][] = new int[n][2];
        
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        
        for (int i = 1; i < n; i++) {
            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i] - fee); // sell
            dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i]); // buy
        }
        return dp[n-1][0];
    }
}

use variables

time: O(n)

space: O(1)

class Solution {
    public int maxProfit(int[] prices, int fee) {
        // fee representing a transaction fee.
        // when sell, there is a additional fee
        // dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i] - fee); // sell
        // dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i]); // buy
        
        if (prices == null || prices.length < 2) return 0;
        int n = prices.length;
        
        int dp0 = 0;
        int dp1 = -prices[0];
        
        for (int i = 1; i < n; i++) {
            int newDp0 = Math.max(dp0, dp1 + prices[i] - fee); // sell
            int newDp1 = Math.max(dp1, dp0 - prices[i]); // buy
            dp0 = newDp0;
            dp1 = newDp1;
        }
        return dp0;
    }
}

Last updated