// C# program for the above approach
using System;
class GFG{
// Stores the values at recursive states
static int[,,] dp = new int[100, 100, 100];
// Function to find the minimum difference
// between sum of two K-length subsets
static int minSumDifference(int[] arr, int n,
int k1, int k2,
int sum1, int sum2)
{
// Base Case
if (n < 0)
{
// If k1 and k2 are 0, then
// return the absolute difference
// between sum1 and sum2
if (k1 == 0 && k2 == 0)
{
return Math.Abs(sum1 - sum2);
}
// Otherwise, return INT_MAX
else
{
return Int32.MaxValue;
}
}
// If the result is already
// computed, return the result
if (dp[n, sum1, sum2] != -1)
{
return dp[n, sum1, sum2];
}
// Store the 3 options
int op1 = Int32.MaxValue;
int op2 = Int32.MaxValue;
int op3 = Int32.MaxValue;
// Including the element in first subset
if (k1 > 0)
{
op1 = minSumDifference(arr, n - 1,
k1 - 1, k2,
sum1 + arr[n],
sum2);
}
// Including the element in second subset
if (k2 > 0)
{
op2 = minSumDifference(arr, n - 1,
k1, k2 - 1, sum1,
sum2 + arr[n]);
}
// Not including the current element
// in both the subsets
op3 = minSumDifference(arr, n - 1,
k1, k2,
sum1, sum2);
// Store minimum of 3 values obtained
dp[n, sum1, sum2] = Math.Min(op1,
Math.Min(op2, op3));
// Return the value for
// the current states
return dp[n, sum1, sum2];
}
// Driver Code
static public void Main()
{
int[] arr = { 12, 3, 5, 6, 7, 17 };
int K = 2;
int N = arr.Length;
for(int i = 0; i < 100; i++)
{
for(int j = 0; j < 100; j++)
{
for(int k = 0; k < 100; k++)
{
dp[i, j, k] = -1;
}
}
}
Console.WriteLine(minSumDifference(arr, N - 1, K,
K, 0, 0));
}
}
// This code is contributed by rag2127