Maximizing profit for given stock quotes

后端 未结 9 1902
無奈伤痛
無奈伤痛 2020-12-07 09:45

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

9条回答
  •  一向
    一向 (楼主)
    2020-12-07 10:34

    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;
            }
    

提交回复
热议问题