Java solution O(n)


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

Log in to reply
 

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