Update MinimumSumPartition.java

fix code issue
This commit is contained in:
tribbleofjim 2020-09-06 12:31:11 +08:00 committed by GitHub
parent 6f9d13bfed
commit e7193aab8a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -20,56 +20,73 @@ import java.lang.*;
import java.io.*; import java.io.*;
public class MinimumSumPartition public class MinimumSumPartition
{ {
public static void main (String[] args) public static int subSet(int arr[]){
{ int n = arr.length;
Scanner sc = new Scanner(System.in); int sum = getSum(arr);
int t = sc.nextInt(); boolean dp[][] = new boolean[n+1][sum+1];
while(t-->0) for(int i = 0; i < n; i++){
{ dp[i][0] = true;
int n = sc.nextInt(); }
int arr[] = new int[n]; for(int j = 0; j < sum; j++){
int sum = 0; dp[0][j] = false;
for(int i = 0;i < n;i++) }
{
arr[i] = sc.nextInt(); //fill dp array
sum += arr[i]; for(int i = 1; i <= n; i++){
} for(int j = 1; j <= sum; j++){
int ans[] = new int[sum]; if(arr[i-1] < j){
ans = subset(arr,sum); dp[i][j] = dp[i-1][j - arr[i-1]] || dp[i-1][j];
int min = Integer.MAX_VALUE; }
for (int i = 0; i < ans.length; i++) else if(arr[i-1] == j){
min = Math.min(min,(sum-2*ans[i])); dp[i][j] = true;
System.out.println(min); }
} else{
sc.close(); dp[i][j] = dp[i-1][j];
} }
static int[] subset(int arr[],int sum) }
{ }
int n = arr.length;
boolean dp[][] = new boolean[n+1][sum+1]; // fill the index array
for(int i = 0; i <= n; i++) int index[] = new int[sum];
dp[i][0] = true; int p = 0;
for(int i = 1; i <= sum; i++) for(int i = 0; i <= sum / 2; i++){
dp[0][i] = false; if(dp[n][i]){
// subset sum concept index[p++] = i;
for(int i = 1; i <= n; i++) }
{ }
for(int j = 1; j <= sum; j++)
{ return getMin(index, sum);
if(arr[i-1] <= j) }
dp[i][j] = dp[i-1][j-arr[i-1]] || dp[i-1][j];
else public static int getSum(int arr[]){
dp[i][j] = dp[i-1][j]; if(arr.length <= 0){
} return 0;
} }
//storing last dp column whose value is true till sum/2 int sum = 0;
int index[] = new int[sum]; for(int i = 0; i < arr.length; i++){
int p = 0; sum += arr[i];
for(int i = 0 ; i <= sum / 2; i++) }
{ return sum;
if(dp[n][i] == true) }
index[p++] = i;
} public static int getMin(int arr[], int sum){
return index; if(arr.length <= 0){
} return 0;
}
int min = Integer.MAX_VALUE;
for(int i = 0; i < arr.length; i++){
min = Math.min(min, (sum - 2*arr[i]));
}
return min;
}
public static void main(String args[]){
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int arr[] = new int[n];
for(int i = 0 ; i<n; i++){
arr[i] = in.nextInt();
}
System.out.println(subSet(arr));
}
} }