Java Solution O(n)


  • 0
    S
    
    public class Solution {
        public int maxProfit(int[] prices) {
             if(prices.length == 0)
             {
                return 0;
             }
            
            int buy = prices[0];
            int sell = prices[0];
            int b = 0;
            int s = 0;
            int profit = 0;
            
           
            for(int i = 1; i < prices.length; i++)
            {
                if(prices[i] < buy)
                {
                    buy = prices[i];
                    b = i;
                    sell = 0;
                    s = 0;
                }
                else if(prices[i] > sell)
                {
                    sell = prices[i];
                    s = i;
                }
                
                if(b < s)
                {
                    int temp = sell - buy;
                    if(temp > profit)
                    {
                        profit = temp;
                    }
                }
            }
            
            return profit;
        }
    }
    
    

Log in to reply
 

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