imashutosh51

0/1 Knapsack

Mar 26th, 2026
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.83 KB | None | 0 0
  1. '''
  2. Knanpsack 0/1
  3. if enough space in knapsack remaining, then either you can take it(& add it's profit) or avoid it, else you will have to avoid
  4. and consider the maximum profit out of these cases.
  5. base case:
  6. 1)When no space in knapsack, so no items can be pushed, so no profit, return 0
  7. 2)When no elements are there, so no profit can be made, return 0
  8. '''
  9. def fun(w,n,val,wt,dp):
  10.     if w<=0:
  11.         return 0
  12.     if n<0:
  13.         return 0
  14.     if dp[w][n]!=-1:
  15.         return dp[w][n]
  16.     take=0
  17.     if w>=wt[n]:
  18.         take=val[n]+fun(w-wt[n],n-1,val,wt,dp) #take profit due to including the item
  19.     not_take=fun(w,n-1,val,wt,dp)
  20.     dp[w][n]=max(take,not_take)
  21.     return dp[w][n]
  22.    
  23. class Solution:
  24.     def knapsack(self, W, val, wt):
  25.         dp=[[-1]*len(wt) for _ in range(W+1)]
  26.         return fun(W,len(wt)-1,val,wt,dp)
  27.  
Advertisement
Add Comment
Please, Sign In to add comment