namespace MaxProfitKTransactions
public static void Main()
int[] prices = { 5, 11, 3, 50, 60, 90 };
Console.WriteLine($"Максимальная прибыль от {k} сделок: " + MaxProfit(prices, k));
prices = new int[] { 12, 14, 17, 10, 14, 13, 12, 15 };
Console.WriteLine($"Максимальная прибыль от {k} сделок: " + MaxProfit(prices, k));
prices = new int[] { 100, 30, 15, 10, 8, 25, 80 };
Console.WriteLine($"Максимальная прибыль от {k} сделок: " + MaxProfit(prices, k));
static int MaxProfit(int[] prices, int k)
var totalDays = prices.Length;
if (totalDays == 0) return 0;
int[] oddProfits = new int[totalDays];
int[] evenProfits = new int[totalDays];
int[] previousProfits, currentProfits;
for (int transaction = 1; transaction <= k; transaction++)
if (transaction % 2 == 0)
previousProfits = oddProfits;
currentProfits = evenProfits;
previousProfits = evenProfits;
currentProfits = oddProfits;
int maxIncomeSoFar = int.MinValue;
for (int day = 1; day < totalDays; day++)
maxIncomeSoFar = Math.Max(maxIncomeSoFar, previousProfits[day - 1] - prices[day - 1]);
currentProfits[day] = Math.Max(currentProfits[day - 1], maxIncomeSoFar + prices[day]);
return (k % 2 == 0) ? evenProfits[totalDays - 1] : oddProfits[totalDays - 1];