Thursday, December 18, 2014

Best Time to Buy and Sell Stock

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: greedy method

My thought is to slide the window of minIdx and maxIdx. Another solution is much more concise.
1.
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int n=prices.size();
       
        if(n<2)
           return 0;
          
        int minp=prices[0], maxp=prices[1];
        int minIdx=0, maxIdx=1;
        int maxProfit = maxp-minp;
        for (int i=1; i<n; i++)
        {
            if (prices[i]<minp)
               {
                   minp=prices[i];
                   minIdx = i;
                   if (minIdx>=maxIdx)
                   {
                    maxp=prices[i];
                    maxIdx=i;                  
                   }
               }
            if (prices[i]>maxp)
                {
                    maxp=prices[i];
                    maxIdx=i;
                }
            int tmp = maxp-minp;
            if(tmp>maxProfit)
              {
                  maxProfit=tmp;
              }
        }
       
        return maxProfit;
    }
};

2.

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        int n=prices.size();
       
        if(n<2)
           return 0;
          
        int minp=prices[0],maxProfit = 0;
        for (int i=1; i<n; i++)
        {
            maxProfit = max(maxProfit, prices[i]-minp);
            minp=min(prices[i],minp);
        }
       
        return maxProfit;
    }
};

No comments:

Post a Comment