I was revising DP. I thought of this question. Then I searched and I get this question but without a proper answer.
So here is the complete code (along with comments ): Hope it is useful.
sample image of table
//exactly same concept as subset-sum(find the minimum difference of subset-sum)
public class Main
{
public static int minSubSetSum(int[] arr,int n,int sum,int x){
boolean[][] t=new boolean[n+1][sum+1];
//initailization if n=0 return false;
for(int i=0;i<sum+1;i++)
t[0][i]=false;
//initialization if sum=0 return true because of empty set (a set can be empty)
for(int i=0;i<n+1;i++)
t[i][0]=true; //here if(n==0 && sum==0 return true) has been also initialized
//now DP top-down
for(int i=1;i<n+1;i++)
for(int j=1;j<sum+1;j++)
{
if(arr[i-1]<=j)
t[i][j]=t[i-1][j-arr[i-1]] || t[i-1][j]; // either include arr[i-1] or not
else
t[i][j]=t[i-1][j]; //not including arr[i-1] so sum is not deducted from j
}
//now as per question we have to take all element as it can be present in set1
//if not in set1 then in set2 ,so always all element will be a member of either set
// so we will look into last row(when i=n) and we have to find min_sum(j)
int min_sum=Integer.MAX_VALUE;
for(int j=x;j<=sum;j++)
if(t[n][j]==true){ //if in last row(n) w.r.t J , if the corresponding value true then
min_sum=j; //then that sum is possible
break;
}
if(min_sum==Integer.MAX_VALUE)
return -1;// because that is not possible
return min_sum;
}
public static void main(String[] args) {
int[] arr=new int[]{4,5,8,10,10};
int x=15;
int n=arr.length;
int sum=0;
for(int i=0;i<n;i++)
sum=sum+arr[i];
System.out.println("Min sum can formed greater than X is");
int min_sum=minSubSetSum(arr,n,sum,x);
System.out.println(min_sum);
}
}
As the problem was N-P complete so with DP time complexity reduces to
T(n)=O(n*sum)
and space complexity =O(n*sum);
x
, or any subset>=x
but with the minimum number of elements? – biziclop