O(n) time java code


  • 1
    J
    public class Solution {
        public int maxProfit(int[] prices) {
            if (prices.length == 0 | prices.length == 1)
                return 0;
            int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE, profit = 0;
            for (int x = 0; x < prices.length; x++){
                if ((prices[x] - min) > profit){
                    profit = prices [x] - min;
                    max = prices[x];
                }
                if (prices[x] < min)
                    min = prices[x];
            }
            return profit;
            
        }
    }

  • 0
    X

    Does the max variable do anything?


Log in to reply
 

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