Interview Question Categories

STOCK QUOTE PROBLEM

STOCK QUOTE PROBLEM

/* Given a list of stock quotes over a month of time,
 * Return the buy day and sell day which gives the max
 * profit.
*/ 
namespace StockQuoteProblem
{
    class StockQuote
    {
        public DateTime Date{get; private set;}
        public int Quote { get; private set; }

        public StockQuote(DateTime d, int q)
        {
            Date = d;
            Quote = q;
        }
    }
    class Program
    {
        //Fetch Buy day and sell day
        
        static void GetBuyAndSellDay(StockQuote[] q)
        {
            StockQuote small = q[0];
            DateTime BuyDay = q[0].Date;
            DateTime SellDay = default(DateTime);
       
            int profit = 0;

            for (int i = 1; i < q.Length;i++ )
            {
                if (q[i].Quote > small.Quote)
                {
                    if (q[i].Quote - small.Quote > profit)
                    {
                        BuyDay = small.Date;
                        SellDay = q[i].Date;
                        profit = q[i].Quote - small.Quote;
                    }
                }
                else
                {
                    small = q[i];
                }
            }
            Console.WriteLine(profit+"  "+BuyDay+"  "+SellDay);
        }

        
        static void Main(string[] args)
        {
            int[] Quotes = { 2, 3, 5, 6, 5, 9, 5, 100};

            GetMaxProfit(Quotes);

            StockQuote[] StockValues = {  new StockQuote(new DateTime(2012, 1, 1), 2 ),
                                          new StockQuote(new DateTime(2012, 1, 2), 2 ),
                                          new StockQuote(new DateTime(2012, 1, 3), 20 ),
                                          new StockQuote(new DateTime(2012, 1, 4), 10 ),
                                          new StockQuote(new DateTime(2012, 1, 5), 15 ),
                                          new StockQuote(new DateTime(2012, 1, 6), 18 ),
                                          new StockQuote(new DateTime(2012, 1, 7), 30 ),
                                          new StockQuote(new DateTime(2012, 1, 8), 16 ),
                                          new StockQuote(new DateTime(2012, 1, 9), 24 ),
                                          new StockQuote(new DateTime(2012, 1, 10), 40 ),
                                          new StockQuote(new DateTime(2012, 1, 11), 1 ),
                                          new StockQuote(new DateTime(2012, 1, 12), 38 ),
                                          new StockQuote(new DateTime(2012, 1, 13), 2 ),
                                       };
            GetBuyAndSellDay(StockValues);
           

        }
    }
}

No comments:

Post a Comment