Saturday, December 27, 2014

Best Time to Buy and Sell Stock (LeetCode Array)

Question: Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Idea: Scan the array from left to right. For each price, test how much profit can get if sell at current price. Therefore the problem is to cache the lowest price appeared before.

Time: O(n) Space: O(1)

Code: 
 public class Solution {  
   public int maxProfit(int[] prices) {  
     if(prices==null||prices.length<=1)  
     {  
       return 0;  
     }  
     int lowestBuy=prices[0];  
     int maxProfit=0;  
     for(int i=1;i<prices.length;i++)  
     {  
       maxProfit=Math.max(maxProfit,prices[i]-lowestBuy);  
       lowestBuy=Math.min(lowestBuy,prices[i]);  
     }  
     return maxProfit;  
   }  
 }  

No comments:

Post a Comment