I was asked this question while interviewing for a startup and saw this again in the recent contest at
Code Sprint:systems
**The question :
You are
private static int MaxProfit(int[] A)
{
if (A.Length == 0)
return 0;
Stack repositoryStack = new Stack();
int maxProfit = 0;
int tempProfit;
for (int i = 0; i < A.Length; i++)
{
if (repositoryStack.Count == 0)
{
repositoryStack.Push(i);
continue;
}
while (repositoryStack.Count != 0 && A[i] < A[repositoryStack.Peek()])
{
repositoryStack.Pop();
}
if (repositoryStack.Count != 0 && A[i] > A[repositoryStack.Peek()])
{
tempProfit = A[i] - A[repositoryStack.Peek()];
if (tempProfit > maxProfit)
maxProfit = tempProfit;
}
if(repositoryStack.Count == 0)
repositoryStack.Push(i);
}
return maxProfit;
}