Answer to Question #325290 in C# for Anji

Question #325290

you want tobuy a particular stock at its loerest price andsell it later at its highest price,since the stock market is unpredictable,yousteal the price plans of a company for this stockfor the next N days.

Find the best price you can get to buy this stock to achieve maximum profit.

Note:The initial price of the stock is 0. 


1
Expert's answer
2022-04-09T17:55:31-0400
    internal class Program
    {
        class Proffit
        {
            public static int MaxProfit(int[] price, int start, int end)
            {
                int profit = 0;
                for (int i = start; i < end; i++)
                {
                    for (int j = i + 1; j <= end; j++)
                    {
                        if (price[j] > price[i])
                        {
                            int curr_profit = price[j] - price[i]
                                            + MaxProfit(price, start, i - 1)
                                            + MaxProfit(price, j + 1, end);
                            
                            profit = Math.Max(profit, curr_profit);
                        }
                    }
                }


                return profit;
            }
        }
        static void Main()
        {
            Console.Write("Enter number of days: ");
            int N = int.Parse(Console.ReadLine());
            Console.Write("Enter the price for each day:");
            int[] pricePlans = new int[N];
            for (int i = 0; i < N; i++)
            {
                pricePlans[i] = int.Parse(Console.ReadLine());
            }
            Console.WriteLine($"Possible maximum profit: {Proffit.MaxProfit(pricePlans,0,pricePlans.Length-1)}");
            Console.ReadKey();
        }
    }

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS