imashutosh51

Minimum Subset Sum Difference

Mar 5th, 2026
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.47 KB | None | 0 0
  1. '''
  2. 0/1 Knapsack-> Here the rows are all the elments indices and columns would be the range of minimum to maximum difference so row=n and col=sum(arr)+1
  3. Minimum difference between sum of two partitioned sets can be 0 and maximum can be sum(arr) when all the elements in one set.
  4. - we will keep the cur variable which will have 0 in beginning and shows the sum of the current set.
  5. - We can traverse either when our cur_sum> sum(arr)//2 because once half of the sum is there, adding more numbers will make the difference bigger.
  6. - We can stop when we skipped a lot of elements so cur< sum(arr)//2 but you reach at the end of the arr(ie. n<0) because no elements left now.
  7. - In the above two coditon set1_sum=cur, set2_sum=sum(arr)-cur so their difference= abs(total-cur-cur) ie abs(total-2*cur)
  8. - Once we get values from take and not_take, we will update the dp table with the minimum value of them.
  9.  
  10. Base Case:
  11. 1)When cur>sum(arr)//2 or n<0: return abs(total-2*cur)
  12. '''
  13.  
  14.  
  15. def fun(arr, cur, n,dp,total):
  16.     if cur> total//2:
  17.         return abs(total-2*cur)
  18.     if n<0:
  19.         return abs(total-2*cur)
  20.  
  21.     if dp[n][cur]!=-1:
  22.         return dp[n][cur]
  23.     take=fun(arr,cur+arr[n],n-1,dp,total)
  24.     not_take=fun(arr,cur,n-1,dp,total)
  25.     dp[n][cur]=min(take,not_take)
  26.     return dp[n][cur]
  27.  
  28. class Solution:
  29.     def minDifference(self, arr):
  30.         l,r=0,sum(arr)+1
  31.         dp=[[-1]*r for _ in range(len(arr))]
  32.         return fun(arr,0,len(arr)-1,dp,sum(arr))
  33.  
  34.        
Advertisement
Add Comment
Please, Sign In to add comment