Friday, February 20, 2015

Best Time to Buy and Sell Stock

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.

------------------------------ codes ---------------------------------------------------
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if (prices.size() <= 1) return 0;
        vector<int> min(prices.size(), prices[0]);
        for (int i = 1; i < prices.size(); i++) {
            if (prices[i] < min[i-1]) {
                min[i] = prices[i];
            } else {
                min[i] = min[i-1];
            }
        }
        int max = 0;
        for (int i = prices.size() - 1; i >= 1; i--) {
            if (prices[i] - min[i] > max) {
                max = prices[i] - min[i];
            }
        }
        return max;
    }
};
----------------------------- read codes --------------------------------------------------
class Solution {
public:
    int maxProfit(vector<int> &prices) {
        if (prices.size() <= 1) return 0;
        //using a single var to store the min until now
        int cur_min = prices[0];
        int max = 0;
        for (int i = 1; i < prices.size(); i++) {
            if (prices[i] < cur_min) {
                cur_min = prices[i];
            }
            if (prices[i] - cur_min > max) {
                max = prices[i] - cur_min;
            }
        }
        return max;
    }
};
----------------------------- read codes --------------------------------------------------
class Solution { vector<int> price; public: int maxProfit(vector<int> &prices) { int n = prices.size(),i,temp,max_profit=INT_MIN; if(n<=1) return 0; temp = prices[n-1]; for(i=n-2;i>=0;i--) { if(prices[i]>temp) temp = prices[i]; //here, temp -> max. selling price possible at time = i prices[i] = temp - prices[i]; //Now, prices[i] will store the max. profit if the stock was bought at time = i //updating max. profit. if(prices[i]>max_profit) max_profit = prices[i]; } return max_profit; } };

No comments:

Post a Comment