Simple Java Solution, O(n) time and O(1) space


  • 0
    M
    public class Solution {
        public int maxProfit(int[] prices) {
            int max = 0, i = 0, j = 1;
            
            while (i < prices.length - 1 && j < prices.length) {
                if (prices[i] > prices[j]) i = j;
                else max = Math.max(max, prices[j++] - prices[i]);
            }
    
            return max;
        }
    

Log in to reply
 

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