using
System;
using
System.Collections.Generic;
class
GFG {
static
int
maxProfit(
int
n,
int
k,
int
[] prices)
{
int
ans = 0;
int
buy = 0;
int
sell = 0;
List<
int
[]> transaction =
new
List<
int
[]>();
List<
int
> profits =
new
List<
int
>();
while
(sell < n) {
buy = sell;
while
(buy < n - 1
&& prices[buy] >= prices[buy + 1])
buy += 1;
sell = buy + 1;
while
(sell < n
&& prices[sell] >= prices[sell - 1])
sell += 1;
while
(transaction.Count != 0
&& prices[buy] < prices
[transaction[transaction.Count
- 1][0]]) {
int
[] p
= transaction[transaction.Count - 1];
profits.Add(prices[p[1] - 1]
- prices[p[0]]);
transaction.RemoveAt(transaction.Count - 1);
}
profits.Sort();
while
(transaction.Count != 0
&& prices[sell - 1] > prices
[transaction[transaction.Count
- 1][1]
- 1]) {
int
[] p
= transaction[transaction.Count - 1];
profits.Add(prices[p[1] - 1] - prices[buy]);
buy = p[0];
transaction.RemoveAt(transaction.Count - 1);
}
int
[] elem = { buy, sell };
transaction.Add(elem);
}
profits.Sort();
while
(transaction.Count != 0) {
profits.Add(
prices[transaction[transaction.Count - 1][1]
- 1]
- prices[transaction[transaction.Count - 1]
[0]]);
transaction.RemoveAt(transaction.Count - 1);
}
profits.Sort();
while
(k != 0 && profits.Count != 0) {
ans += profits[0];
profits.RemoveAt(0);
k -= 1;
}
return
ans;
}
public
static
void
Main(
string
[] args)
{
int
k = 3;
int
[] prices
= { 1, 12, 10, 7, 10, 13, 11, 10, 7, 6, 9 };
int
n = prices.Length;
Console.Write(
"Maximum profit is "
+ maxProfit(n, k, prices));
}
}