Greedy, Java, O(n) time, O(1) space


  • 0

    If the stock prices drops below max - fee, we can drop the stock in the max day and buy in new stocks.

        public int maxProfit(int[] prices, int fee) {
            if (prices == null || prices.length == 0) {
                return 0;
            }
            int min = prices[0], max = prices[0];
            int profit = 0;
            int curProfit = 0;
            for (int i = 1; i < prices.length; i++) {
                min = Math.min(min, prices[i]);
                max = Math.max(max, prices[i]);
                curProfit = Math.max(curProfit, prices[i] - min - fee);
                if (max - prices[i] >= fee) {
                    profit += curProfit;
                    curProfit = 0;
                    min = prices[i];
                    max = prices[i];
                }
            }
            return profit + curProfit;
        }
    

Log in to reply
 

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