April 08, 2019

121. Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

One pass. Time = O(n), space = O(1)

class Solution {
    public int maxProfit(int[] prices) {
        if (prices.length <= 1) {
            return 0;
        }
        int lowest = prices[0];
        int maxProfit = 0;
        for (int i = 0; i < prices.length; i++) {
            maxProfit = Math.max(prices[i] - lowest, maxProfit);
            lowest = Math.min(lowest, prices[i]);
        }
        return maxProfit;
    }
}
comments powered by Disqus