Advertisement
Oppenheimer

minimum subset sum difference

Aug 14th, 2022
24
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.02 KB | None | 0 0
  1. // S1 -s2 min means s1+s2 = total sum ..
  2. // we need to find min (S - 2*s1)  .. so we itrate till s/2. and find the minimum diff of s and 2*s1
  3.  
  4. int solve(vector<int> value){
  5.     int  n = value.size();
  6.     int sum=0;
  7.     for(int a=0;a<n;a++)sum+=value[a];
  8.    
  9.     vector<vector<bool>> dp (n+1 ,vector<bool>(sum+1,false));
  10.     // a represents the ath element .. b represents the knapsack present
  11.    
  12.     for(int a=0;a<=n;a++)dp[a][0] = true;// sum 0 is possible even if do not select anything
  13.    
  14.     for(int a=1;a<=n;a++){
  15.         for(int b=1;b<=sum;b++){
  16.             if(value[a-1]<=b){
  17.             dp[a][b] = dp[a-1][b-value[a-1]] || dp[a-1][b]; //either i choose the ath element or not
  18.             }else{
  19.             dp[a][b] = dp[a-1][b]; // cant choose the ath element becuase its weight is more
  20.             }
  21.         }
  22.     }
  23.     int mn = INT_MAX;
  24.     for(int a=0;a<=sum/2;a++){
  25.         if(dp[n][a] == true){
  26.         //means sum a exists
  27.             mn = min(mn , sum - 2*a);
  28.         }
  29.     }
  30.     return mn;
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement