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.
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();
}
}
Comments
Leave a comment