geeksforgeeks@ Minimum sum partition (Dynamic programming)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.