runnig

Best Time to Buy and Sell Stock (done)

Feb 19th, 2013
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.82 KB | None | 0 0
  1. /*
  2. http://leetcode.com/onlinejudge#question_121
  3.  
  4. Best Time to Buy and Sell Stock
  5.  
  6.  
  7. Say you have an array for which the ith element is the price of a given stock on day i.
  8.  
  9. 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.
  10.  
  11. */
  12. class Solution {
  13. public:
  14.     int maxProfit(vector<int> &prices) {
  15.        
  16.         const size_t N = prices.size();
  17.        
  18.         if(N <= 1) { return 0; }
  19.        
  20.         int minSoFar = prices[0];
  21.         int maxProfit = 0;
  22.        
  23.         for(size_t i = 1; i < N; ++i)
  24.         {
  25.             if(prices[i] < minSoFar) { minSoFar = prices[i]; }
  26.             else{ maxProfit = max(maxProfit, prices[i] - minSoFar); }
  27.         }
  28.        
  29.         return maxProfit;
  30.        
  31.     }
  32. };
Advertisement
Add Comment
Please, Sign In to add comment