Solution keeping last bought price [1 ms]


  • 0
    S
    public int maxProfit(int[] prices) {
            if (prices.length == 0) return 0;
            
            // Define profit & first bought stock price
            int total = 0, lastBought = prices[0];
            // Iterate starting from 1, because we've already bought at 0
            for (int i = 1; i < prices.length; ++i) {
                
                // If there is a lower stock price, buy it
                if (prices[i] < lastBought)
                    lastBought = prices[i];
               
                // If price had gone up, sell for profit
                // and buy again
                if (prices[i] > lastBought) {
                    total += prices[i] - lastBought;
                    lastBought = prices[i];
                }
                
            }
            return total;
        }
    

Log in to reply
 

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