imashutosh51

Unbounded Knapsack

Mar 26th, 2026
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.79 KB | None | 0 0
  1. '''
  2. Unbounded Knapsack:
  3. if current capacity left in knapsack is more than the current item then either you take it or not take it and you can not take it too.
  4. Same as 0/1 Knapsack but if you take it, then don't skip this element because you can take it again and again until you don't exceed the capacity
  5. of the knapsack.
  6. '''
  7. def fun(w,n,val,wt,dp):
  8.     if n<0:
  9.         return 0
  10.     if w<0:
  11.         return 0
  12.     if dp[n][w]!=-1:
  13.         return dp[n][w]
  14.     take=0
  15.     if w>=wt[n]:
  16.         take=val[n]+fun(w-wt[n],n,val,wt,dp)
  17.     not_take=fun(w,n-1,val,wt,dp)
  18.     dp[n][w]=max(take,not_take)
  19.     return dp[n][w]
  20. class Solution:
  21.     def knapSack(self, val, wt, capacity):
  22.         dp=[[-1]*(capacity+1) for _ in range(len(wt))]
  23.         return fun(capacity,len(val)-1,val,wt,dp)
  24.        
Advertisement
Add Comment
Please, Sign In to add comment