Monday, January 21, 2013

Best time to buy and sell stock 2

Problem:

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.

Solution:

class Solution {
public:
    int maxProfit(vector<int> &prices) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (prices.size() < 2) {
            return 0;
        }
        int minSoFar = prices[0];
        int maxSoFar = prices[0];
        int bestBuy = 0;
        int maxBestBuy = 0;
        int sum = 0;
        int it;
        for(it = 1; it < prices.size(); it++) {
            if (prices[it] >= maxSoFar) {
                maxSoFar = prices[it];
                bestBuy = maxSoFar - minSoFar;
                maxBestBuy = max(bestBuy, maxBestBuy);
            } else {
                sum += maxBestBuy;
                maxBestBuy = 0;
                minSoFar = prices[it];
                maxSoFar = prices[it];
            }
        }
        return sum + maxBestBuy;
    }
};

1 comment:

  1. This is very nice method to buy. This is not only limited to Philippians but it can apply all over the world. I have also find another interesting guide to buy and sell stock. I like to share here with all fello trader.So they get benefit of it. Get best guide to buy and sell stock on http://jtkuwar.com

    ReplyDelete