Simple Java solution


  • 1
    S
    public class Solution {
        public int maxProfit(int[] prices) {
                  
           if(prices.length==0 || prices==null) return 0;
           
    // buy stock on the first day, if you sell it today you will get no profit
            int min=prices[0], profit=0;
            
    // from the next day keep on checking if you can make more profit by selling today  and  
    // if it would have been better to buy stock at today's rate.
            for(int i=1;i<prices.length;i++){
                if(prices[i]-min> profit) profit=prices[i]-min;
                if(prices[i]<min) min=prices[i];
            }
          
            return profit;
        }
    }
    

Log in to reply
 

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