using System;
using System.Collections.Generic;
public class GFG {
static int B;
static int[, , ] dp = new int[501, 201, 2];
static List<int> pre_sum = new List<int>();
public static int solve(int j, int i, int b, int[] arr)
{
// If the result has already been
// calculated return that result
if (dp[i, j, b] != -1)
return dp[i, j, b];
// If i has reached the end of the
// array return 0
if (i == B)
return 0;
// If we have exhausted the number of
// transaction return 0
if (j == 0)
return 0;
int res;
if (b == 1)
res = Math.Max(-pre_sum[i]
+ solve(j, i + 1, 0, arr),
solve(j, i + 1, 1, arr));
else
res = Math.Max(
pre_sum[i] + solve(j - 1, i + 1, 1, arr),
solve(j, i + 1, 0, arr));
// Return the result
return dp[i, j, b] = res;
}
public static int maxSum(int K, int N, int[] arr)
{
for (int i = 0; i < N + 1; i++) {
pre_sum.Add(0);
}
// Finding prefix sum of array arr[]
for (int i = 1; i <= N; i++)
pre_sum[i] = pre_sum[i - 1] + arr[i - 1];
// Initializing DP with -1
for (int i = 0; i < 501; i++) {
for (int j = 0; j < 201; j++) {
dp[i, j, 0] = dp[i, j, 1] = -1;
}
}
// Copying n to global B
B = N + 1;
// Function to find maximum
return solve(K, 0, 1, arr);
}
// Driver code
static public void Main()
{
// Test case 1
int[] arr1 = { 4, 1, -3, 7, -5, 6, -2, 1 };
int K1 = 3;
int N1 = arr1.Length;
// Function call
Console.WriteLine(maxSum(K1, N1, arr1));
// Test case 2
int[] arr2 = { 8, -1, 4, 2, 6, -6, 4, -1 };
int K2 = 2;
int N2 = arr2.Length;
// Function call
Console.WriteLine(maxSum(K2, N2, arr2));
}
}
// This code is contributed by Rohit Pradhan