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

Your are given an array of integers prices, for which the i-th element is the price of a given stock on day i; and a non-negative integer fee representing a transaction fee.

class Solution {
    public int maxProfit(int[] prices, int fee) {
        // sold[i] = Math.max(sold[i-1], hold[i-1]+prices[i]-2);
        // hold[i] = Math.max(hold[i-1], sold[i-1]-prices[i]);
        // base sold[0] = 0, hold[0]=-prices[0];
        
        if (prices.length<1) return 0;
        int sold=0, hold=-prices[0];
        for (int i=1; i<prices.length;i++){
            int temp = sold;
            sold = Math.max(sold, hold+prices[i]-fee);
            hold = Math.max(hold, temp-prices[i]);
        }
        
        return Math.max(sold, hold);
    }
}

Last updated