my greedy solution


  • 0
    L

    '''

    public int maxProfit(int[] prices, int fee) {
        if (prices.length==0){
            return 0;
        }
        int profit = 0;
        int hold = prices[0];
        int sell = hold;
        boolean hasBuy = false;
        for (int i=1;i<prices.length;i++){
            if (!hasBuy && prices[i] < hold){
                hold = prices[i];
            }else if (!hasBuy && prices[i] - hold > fee){
                hasBuy = true;
                sell = prices[i];
            }else if (hasBuy && prices[i] > sell){
                sell = prices[i];
            }else if (hasBuy && sell - prices[i] >fee ){
                profit += sell - hold - fee;
                hasBuy = false;
                hold = prices[i];
            }
        }
        if (hasBuy){
            profit += sell - hold - fee;
        }
        return profit;      
    }
    

    '''


Log in to reply
 

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