Java, 3 variables


  • 0
    O
    public int maxProfit(int[] prices, int fee) {
            
            if (prices.length < 2) return 0;
            
            int running = 0;
            int high = 0;
            int profit = 0;
            
            for (int i = 1; i < prices.length; i++) {
                
                running += prices[i] - prices[i-1];
                high = Math.max(high, running);
                
                if (running < 0 || high - fee > running || i == prices.length-1) {
                    profit = Math.max(profit + high - fee, profit);
                    running = 0;
                    high = 0;
                }
            }
            
            return profit;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.