-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmin_sum_partition.java
90 lines (74 loc) · 2.08 KB
/
min_sum_partition.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG {
static int findMinRec(int arr[], int n)
{
// Calculate sum of all elements
int sum = 0;
for (int i = 0; i < n; i++)
sum += arr[i];
// Create an array to store
// results of subproblems
boolean dp[][] = new boolean[n + 1][sum + 1];
// Initialize first column as true.
// 0 sum is possible with all elements.
for (int i = 0; i <= n; i++)
dp[i][0] = true;
// Initialize top row, except dp[0][0],
// as false. With 0 elements, no other
// sum except 0 is possible
for (int i = 1; i <= sum; i++)
dp[0][i] = false;
// Fill the partition table
// in bottom up manner
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= sum; j++)
{
// If i'th element is excluded
dp[i][j] = dp[i - 1][j];
// If i'th element is included
if (arr[i - 1] <= j)
dp[i][j] =dp[i][j] || dp[i - 1][j - arr[i - 1]];
}
}
// Initialize difference of two sums.
int diff = Integer.MAX_VALUE;
// Find the largest j such that dp[n][j]
// is true where j loops from sum/2 t0 0
for (int j = sum / 2; j >= 0; j--)
{
// Find the
if (dp[n][j] == true)
{
diff = sum - 2 * j;
break;
}
}
return diff;
}
public static void main (String[] args) {
//code
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
while(t-->0)
{
int n=sc.nextInt();
int arr[]=new int[n];
// int sum=0;
for(int i=0;i<n;i++)
{
arr[i]=sc.nextInt();
//sum+=arr[i];
}
System.out.println(findMinRec(arr, n));
}
}
}
/*output:For Input:
4
1 6 5 11
your output is:
1
*/