Advertisement
imashutosh51

Minimum sum partition

Jul 23rd, 2022 (edited)
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.93 KB | None | 0 0
  1. //Logic:Time complexity : O(N*W) W=total sum of aray
  2. //break the problem in two part,just find all the subset sum possible.Now we have all subset,so search a
  3. //possible subset closest to sum/2 which will give the lowest difference.
  4. //use a dp array of boolean whose all rows except first row denotes an item where all the columns denotes the
  5. //weight is possible or not using till ith items
  6. //eg dp[i][j]=is it possible to get weight j using items (i-1)th of array.
  7. //then in last row,we have all possible subset sum including all the items,so if first subset weight=i,
  8. //second will sum-i,so find minimum difference.
  9.  
  10. class Solution{
  11.  
  12.   public:
  13.     int minDifference(int arr[], int n)  {
  14.         long long int sum=0;
  15.         for(int i=0;i<n;i++) sum+=arr[i];
  16.         vector <vector <bool>> dp(n+1,vector<bool> (sum+1,0));
  17.         for(int i=0;i<=n;i++){
  18.             for(int j=0;j<=sum;j++){
  19.                 if(j==0) dp[i][j]=true; //if 0 weight is possible to have without including any item
  20.                 else if(i==0) dp[i][j]=false; //all the weight from 1 to sum can not be possible with no items
  21.                                            //starting from 1 to sum because for j=0,first if will only get applied
  22.                 else if(j>=arr[i-1]){  //if current array element is smaller than current weight,then either it
  23.                     dp[i][j]=(dp[i-1][j] || dp[i-1][j-arr[i-1]]);//can be included or not included.
  24.                 }    
  25.                 //we have used two times i-1 in above condition here because ith element of array
  26.                 //can be accessed by i-1 only,i is for dp array but i-1 required for array.
  27.                
  28.                
  29.                 else dp[i][j]=dp[i-1][j];  //if current array element is greater than the j weight,
  30.                                            //then it can't be included.
  31.             }
  32.         }
  33.         int dif=INT_MAX;
  34.         for(int i=sum/2;i>=0;i--){
  35.             if(dp[n][i]) return abs(i-(sum-i));
  36.         }
  37.      
  38.        
  39.     }
  40. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement