714 Best Time to Buy and Sell Stock with Transaction Fee

class Solution {
    public int maxProfit(int[] prices, int fee) {
        if (prices == null || prices.length == 0) return 0;
        int cash = 0, hold = -prices[0];
        for (int i = 1; i < prices.length; i++){
            cash = Math.max(cash, hold + prices[i] - fee);
            hold = Math.max(hold, cash - prices[i]);
        }

        return cash;
    }
}

309 Best Time to Buy and Sell Stock with Cooldown

https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/discuss/75927

class Solution {
    public int maxProfit(int[] prices) {
        int sell = 0, prev_sell = 0;
        int buy = Integer.MIN_VALUE, prev_buy = Integer.MIN_VALUE;

        for (int price : prices){
            prev_buy = buy;
            buy = Math.max(prev_sell - price, buy);
            prev_sell = sell;
            sell = Math.max(prev_buy + price, prev_sell);
        }

        return sell;
    }
}

123 Best Time to Buy and Sell Stock III

class Solution {
    public int maxProfit(int[] prices) {
        int hold1 = Integer.MIN_VALUE, hold2 = Integer.MIN_VALUE;
        int release1 = 0, release2 = 0;

        for (int i : prices){
            release2 = Math.max(release2, hold2 + i);
            hold2 = Math.max(hold2, release1 - i);
            release1 = Math.max(release1, hold1 + i);
            hold1 = Math.max(hold1, -i);
        }

        return release2;
    }
}

188 Best Time to Buy and Sell Stock IV

General solution

class Solution {
    public int maxProfit(int k, int[] prices) {
        if (prices == null || prices.length == 0) return 0;
        if (k > prices.length / 2) return solve(prices);
        int[][] hold = new int[prices.length][k + 1];
        int[][] unhold = new int[prices.length][k + 1];

        hold[0][0] = -prices[0];
        for (int i = 1; i < prices.length; i++) hold[i][0] = Math.max(hold[i - 1][0], -prices[i]);
        for (int j = 1; j <= k; j++) hold[0][j] = -prices[0];

        for (int i = 1; i < prices.length; i++){
            for (int j = 1; j <= k; j++){
                hold[i][j] = Math.max(hold[i - 1][j], unhold[i - 1][j] - prices[i]);
                unhold[i][j] = Math.max(unhold[i - 1][j], hold[i - 1][j - 1] + prices[i]);
            }
        }

        return Math.max(hold[prices.length - 1][k], unhold[prices.length - 1][k]);
    }

    private int solve(int[] prices){
        int ans = 0;
        for (int i = 0; i < prices.length; i++){
            if (i > 0 && prices[i] > prices[i - 1]){
                ans += prices[i] - prices[i - 1];
            }
        }

        return ans;
    }
}

results matching ""

    No results matching ""