Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // S1 -s2 min means s1+s2 = total sum ..
- // we need to find min (S - 2*s1) .. so we itrate till s/2. and find the minimum diff of s and 2*s1
- int solve(vector<int> value){
- int n = value.size();
- int sum=0;
- for(int a=0;a<n;a++)sum+=value[a];
- vector<vector<bool>> dp (n+1 ,vector<bool>(sum+1,false));
- // a represents the ath element .. b represents the knapsack present
- for(int a=0;a<=n;a++)dp[a][0] = true;// sum 0 is possible even if do not select anything
- for(int a=1;a<=n;a++){
- for(int b=1;b<=sum;b++){
- if(value[a-1]<=b){
- dp[a][b] = dp[a-1][b-value[a-1]] || dp[a-1][b]; //either i choose the ath element or not
- }else{
- dp[a][b] = dp[a-1][b]; // cant choose the ath element becuase its weight is more
- }
- }
- }
- int mn = INT_MAX;
- for(int a=0;a<=sum/2;a++){
- if(dp[n][a] == true){
- //means sum a exists
- mn = min(mn , sum - 2*a);
- }
- }
- return mn;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement