Sunday, May 19, 2013

Stocks buy and sell, Max profit

Stock prices are stored in an array in the order of date. How do you get the most profit from a
sequence of stock prices? For example, the most profit to be gained from the sequence of ordered stock prices {9, 11, 5, 7, 16, 1, 4, 2} is 11, bought when the price was 5 and sold when the price was 16.

public static int maxStock(int stock[])
{
if(stock == null || stock.length < 2)
{
return 0;
}

int minStock = stock[0];
int maxDiff = stock[1]-stock[0];

for(int i=2;i<stock.length;i++)
{
if(stock[i-1] < minStock)
minStock = stock[i-1];

int currDiff = stock[i] - minStock;
if(currDiff > maxDiff)
maxDiff = currDiff;
}

return maxDiff;

}

No comments: