121. Best Time to Buy and Sell Stock

time: O(n)

space: O(1)

hint: need to find the largest peak following the smallest valley

keep the min price, and find maxprofit

class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        int min = Integer.MAX_VALUE;
        for (int price : prices) {
            if (price < min) {
                min = price;
            }
            if (price - min > profit) {
                profit = price - min;
            }
        }    
        return profit;
    }
}

Last updated

Was this helpful?