2020-08-02 15:21:33 +08:00
|
|
|
package DynamicProgramming;
|
2020-08-02 13:36:09 +08:00
|
|
|
// Partition a set into two subsets such that the difference of subset sums is minimum
|
|
|
|
|
|
|
|
/*
|
|
|
|
Input: arr[] = {1, 6, 11, 5}
|
|
|
|
Output: 1
|
|
|
|
Explanation:
|
|
|
|
Subset1 = {1, 5, 6}, sum of Subset1 = 12
|
|
|
|
Subset2 = {11}, sum of Subset2 = 11
|
|
|
|
|
|
|
|
Input: arr[] = {36, 7, 46, 40}
|
|
|
|
Output: 23
|
|
|
|
Explanation:
|
|
|
|
Subset1 = {7, 46} ; sum of Subset1 = 53
|
|
|
|
Subset2 = {36, 40} ; sum of Subset2 = 76
|
|
|
|
*/
|
|
|
|
|
|
|
|
import java.util.*;
|
|
|
|
import java.lang.*;
|
|
|
|
import java.io.*;
|
2020-08-02 15:21:33 +08:00
|
|
|
public class MinimumSumPartition
|
|
|
|
{
|
2020-08-02 13:36:09 +08:00
|
|
|
public static void main (String[] args)
|
2020-08-02 15:21:33 +08:00
|
|
|
{
|
|
|
|
Scanner sc = new Scanner(System.in);
|
|
|
|
int t = sc.nextInt();
|
2020-08-02 13:36:09 +08:00
|
|
|
while(t-->0)
|
|
|
|
{
|
2020-08-02 15:21:33 +08:00
|
|
|
int n = sc.nextInt();
|
|
|
|
int arr[] = new int[n];
|
|
|
|
int sum = 0;
|
|
|
|
for(int i = 0;i < n;i++)
|
2020-08-02 13:36:09 +08:00
|
|
|
{
|
2020-08-02 15:21:33 +08:00
|
|
|
arr[i] = sc.nextInt();
|
|
|
|
sum += arr[i];
|
2020-08-02 13:36:09 +08:00
|
|
|
}
|
2020-08-02 15:21:33 +08:00
|
|
|
int ans[] = new int[sum];
|
|
|
|
ans = subset(arr,sum);
|
|
|
|
int min = Integer.MAX_VALUE;
|
|
|
|
for (int i = 0; i < ans.length; i++)
|
|
|
|
min = Math.min(min,(sum-2*ans[i]));
|
2020-08-02 13:36:09 +08:00
|
|
|
System.out.println(min);
|
|
|
|
}
|
2020-08-31 18:36:38 +08:00
|
|
|
sc.close();
|
2020-08-02 13:36:09 +08:00
|
|
|
}
|
|
|
|
static int[] subset(int arr[],int sum)
|
|
|
|
{
|
2020-08-02 15:21:33 +08:00
|
|
|
int n = arr.length;
|
|
|
|
boolean dp[][] = new boolean[n+1][sum+1];
|
|
|
|
for(int i = 0; i <= n; i++)
|
|
|
|
dp[i][0] = true;
|
|
|
|
for(int i = 1; i <= sum; i++)
|
|
|
|
dp[0][i] = false;
|
2020-08-02 13:36:09 +08:00
|
|
|
// subset sum concept
|
2020-08-02 15:21:33 +08:00
|
|
|
for(int i = 1; i <= n; i++)
|
2020-08-02 13:36:09 +08:00
|
|
|
{
|
2020-08-02 15:21:33 +08:00
|
|
|
for(int j = 1; j <= sum; j++)
|
2020-08-02 13:36:09 +08:00
|
|
|
{
|
2020-08-02 15:21:33 +08:00
|
|
|
if(arr[i-1] <= j)
|
|
|
|
dp[i][j] = dp[i-1][j-arr[i-1]] || dp[i-1][j];
|
2020-08-02 13:36:09 +08:00
|
|
|
else
|
2020-08-02 15:21:33 +08:00
|
|
|
dp[i][j] = dp[i-1][j];
|
2020-08-02 13:36:09 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
//storing last dp column whose value is true till sum/2
|
2020-08-02 15:21:33 +08:00
|
|
|
int index[] = new int[sum];
|
|
|
|
int p = 0;
|
|
|
|
for(int i = 0 ; i <= sum / 2; i++)
|
2020-08-02 13:36:09 +08:00
|
|
|
{
|
2020-08-02 15:21:33 +08:00
|
|
|
if(dp[n][i] == true)
|
|
|
|
index[p++] = i;
|
2020-08-02 13:36:09 +08:00
|
|
|
}
|
|
|
|
return index;
|
|
|
|
}
|
|
|
|
}
|