4/13/2014

Leetcode -- Best Time to Buy and Sell Stock

We have a starting point, when prices go above the price at the starting point, we calculate the difference. If we get a larger difference, we log it. Another case, when the price drop bellow the current starting point, we know that we should always buy stock at a lower price. So we update the starting point to this new point.
class Solution {  
 public:  
   int maxProfit(vector<int> &prices) {  
     int last = 0;  
     int max = 0;  
     int diff = 0;  
     for(int i = 0; i < prices.size(); ++i) {  
       if(prices[i] >= prices[last]) {  
         diff = prices[i] - prices[last];  
         if(diff > max) {  
           max = diff;  
         }  
       } else {  
         last = i;  
         diff = 0;  
       }  
     }  
     return max;  
   }  
 };  
changed a bit, but basically the same
class Solution {  
 public:  
   int maxProfit(vector<int> &prices) {  
     int start = 0;  
     int end = prices.size() - 1;  
      if(start >= end) {  
       return 0;  
     }  
     int profit = 0;  
     int last = start;  
     for(int i = start + 1; i <= end; ++i) {  
       if(prices[i] > prices[i - 1]) {  
        profit = max(prices[i] - prices[last], profit);    
       } else {  
         if(prices[i] < prices[last]) {  
           last = i;  
         }  
       }  
     }  
     return profit;  
   }  
 };  

No comments: