imashutosh51

Partitions with Given Difference

Mar 5th, 2026
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. '''
  2. 0/1 Knapsack-> Here it wants all the sets combinations whose difference is diff so obviouse one set sum would be x and the other as x+diff
  3. but x+x+diff==sum(arr) so we can try to get one set whose sum is = (sum(arr)-diff)//2, if we get this then other will automatically x+diff
  4. so problem reduced to find all the subsets of target size (sum(arr)-diff//2).
  5.  
  6. dp table rows will denote all the array indices and column will denote the target we are trying to find. row=0->n-1 and col= 0-> target
  7. so when our target the max number of cols but while summing cur can exceed our target and cur>target is no use of use, because that can't
  8. go in table also(cur> no. of columns) so one more base case at top if cur>target return False
  9.  
  10.  
  11. Base case:
  12. 1)if cur>target: return False
  13. 1) go till the end of the array because if you stop at target, may be some zero we forget to consider for target=5 {0,0,5} as we are coming
  14. from back so when we get 5, we don't go to other 0 but 5+0 is also the 5 only.
  15. so
  16. '''
  17.  
  18. def fun(arr,cur,n,dp,target):
  19.     if cur>target:
  20.         return 0
  21.     if n<0:
  22.         if cur==target:
  23.             return 1
  24.         return 0
  25.     if dp[n][cur]!=-1:
  26.         return dp[n][cur]
  27.     take=0
  28.     if cur+arr[n]<=target:
  29.         take=fun(arr,cur+arr[n],n-1,dp,target)
  30.     not_take=fun(arr,cur,n-1,dp,target)
  31.     dp[n][cur]=take + not_take
  32.     return dp[n][cur]
  33.    
  34. class Solution:
  35.     def countPartitions(self, arr, diff):
  36.         total=sum(arr)
  37.         if (total-diff)%2!=0:
  38.             return 0
  39.            
  40.         target=(total-diff)//2
  41.         dp=[[-1]*(target+1) for _ in range(len(arr))]
  42.         return fun(arr,0,len(arr)-1,dp,target)
  43.        
  44.  
Advertisement
Add Comment
Please, Sign In to add comment