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

;  |     Back to Homepage   |     Back to Code List


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