http://www.practice.geeksforgeeks.org/problem-page.php?pid=166
Minimum sum partition
Given an array, the task was to divide it into a sets S1 and S2 such that the absolute difference between their sums is M Inimum.
Input:
The first line contains a integer ' T ' denoting the total number of test cases. In each test cases, the first line contains an integer ' N ' denoting the size of the array. The second line contains N space-separated integers A1, A2, ..., an denoting the elements of the array.
Output:
In each seperate line print minimum absolute difference.
Constraints:
1<=t<=30
1<=n<=50
1<=a[i]<=50
Example:
Input:
2
4
1 6 5 11
4
36 7 46 40
Output:
1
23
Explaination:
Subset1 = {1, 5, 6}, sum of Subset1 = 12
Subset2 = {One}, sum of Subset2 = 11
ImportJava.util.*;Importjava.lang.*;ImportJava.io.*;classGFG { Public Static intFuncint[] arr) { intn = arr.length, tot = 0; for(inti=0; i<n; ++i) {tot+=Arr[i]; } intHalf = TOT/2, E =half; for(; e>=0;--e) {Boolean[] DP =New Boolean[n + 1] [E + 1]; for(inti=0; i<=n; ++i) {dp[i][0] =true; } for(intI=1; i<=n; ++i) { for(intJ=1; j<=e; ++j) {if(J >= Arr[i-1]) {Dp[i][j]|= Dp[i-1][j] | Dp[i-1][j-arr[i-1]]; } Dp[i][j]|= dp[i-1][j]; } } if(Dp[n][e]) Break; } //System.out.println (e); returnMath.Abs (e-(Tot-e)); } Public Static voidMain (string[] args) {Scanner in=NewScanner (system.in); intTimes =In.nextint (); while(Times > 0) { --Times ; intn =In.nextint (); int[] arr =New int[n]; for(inti=0; i<n; ++i) {Arr[i]=In.nextint (); } System.out.println (func (arr)); } }}
View Code
[email protected] Minimum sum partition (Dynamic programming)