Saturday, February 16, 2013

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
*/
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int size = prices.size();
        if(size<=1) return 0;
        int minv = 0;
       
        int maxProfit = 0;
       
        int i;
        for(i=1; i<size; i++){
          if(prices[i]<prices[minv]) minv = i;
          if(prices[i]-prices[minv]>=maxProfit) maxProfit = max(prices[i]-prices[minv], maxProfit);
        }
       
        return maxProfit;
    }
};

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int i, j;
        int maxProfit = 0;
        int profit;
        int days = prices.size();
        for(i=0;i<days-1;i++){
         for(j=i+1;j<days;j++){
           profit = prices[j] - prices[i];
           if (profit > maxProfit){
           maxProfit = profit;
           }
         }   
        }
        return maxProfit; 
    }
};

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int maxProfit = 0;
        int size = prices.size();
        findMaxProfit(prices, 0, 1, maxProfit, size);
        return maxProfit;
    }
    void findMaxProfit(vector<int> &prices, int i, int j, int & maxProfit, int const size){
       if(i>=j||i>size-2||j>size-1) return;
       int profit = prices[j] - prices[i];
       if(profit > maxProfit) maxProfit = profit;
       findMaxProfit(prices, i+1, j, maxProfit, size);
       findMaxProfit(prices, i, j+1, maxProfit, size);
    }
};

No comments:

Post a Comment