예제 #1
0
        public int MaxProfit(int[] prices)
        {
            possibleSolution currentBest      = null;
            possibleSolution buildingSolution = null;

            for (int i = 0; i < prices.Length; i++)
            {
                findAnyNewBetterSolutionBeatCurrentBest(ref buildingSolution, ref currentBest, prices[i], i);
            }

            if (currentBest == null)
            {
                currentBest = buildingSolution;
            }

            if (buildingSolution != null && buildingSolution.GetProfit() > currentBest.GetProfit())
            {
                currentBest = buildingSolution;
            }

            if (currentBest == null || currentBest.GetProfit() < 0)
            {
                return(0);
            }

            return(currentBest.GetProfit());
        }
예제 #2
0
        private void findAnyNewBetterSolutionBeatCurrentBest(ref possibleSolution buildingSolution, ref possibleSolution currentBest, int v, int i)
        {
            if (buildingSolution == null)
            {
                buildingSolution = new possibleSolution();
            }

            if (!buildingSolution.hasBuyPrice)
            {
                //no buy price, use current one;
                buildingSolution.setBuyPrice(v, i);
                return;
            }

            if (buildingSolution.LowP > v)
            {
                if (buildingSolution.hasSellPrice)
                {
                    //has both buy and sell
                    //check profit with best one
                    if (currentBest == null || currentBest.GetProfit() < buildingSolution.GetProfit())
                    {
                        //if is better solution, replace exsiting one.
                        currentBest = buildingSolution;
                    }

                    //clean current building Solution, setup new one
                    buildingSolution = new possibleSolution();
                    buildingSolution.setBuyPrice(v, i);
                    return;
                }
                else
                {
                    //no buy price. simple set new price as sell price
                    buildingSolution.setBuyPrice(v, i);
                    return;
                }
            }

            if (!buildingSolution.hasSellPrice || buildingSolution.HighP < v)
            {
                buildingSolution.setSellPrice(v, i);
                return;
            }
        }