Sunday, November 14, 2010

Stock buy and sell question.

This is a Google telephone interview question which I found in MITBBS(mitbbs.com).
Here is the question.
Giving the data of stock price for a period, find out the best time to buy and sell this stock.

Some people think it as prediction question, actually it isn't. The soul of this question is giving a int array.
You need to find two position i and j, which a[j]-a[i] is maximum while i < j.

here is one solution provided by one friend from mitbbs which is nice and elegant:

static void BestDay(int[] stockPrices, out int buyDate, out int sellDate)
{
    buyDate = sellDate = 0;
    int maxDiff = 0, minPrice = stockPrices[0], minPriceDate = 0;
    for (int i = 1; i < stockPrices.Length; ++i)
    {
        int price = stockPrices[i]; 
        int diff = price - minPrice;
        if (diff > maxDiff)
        {
            buyDate = minPriceDate;
            sellDate = i;
            maxDiff = diff;
        }

        if (minPrice > price)
        {
            minPrice = price;
            minPriceDate = i;
        }
    }
}

No comments:

Post a Comment