121. Best Time to Buy and Sell Stock

;  |     Back to Homepage   |     Back to Code List


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