Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Unbounded Knapsack:
- 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.
- 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
- of the knapsack.
- '''
- def fun(w,n,val,wt,dp):
- if n<0:
- return 0
- if w<0:
- return 0
- if dp[n][w]!=-1:
- return dp[n][w]
- take=0
- if w>=wt[n]:
- take=val[n]+fun(w-wt[n],n,val,wt,dp)
- not_take=fun(w,n-1,val,wt,dp)
- dp[n][w]=max(take,not_take)
- return dp[n][w]
- class Solution:
- def knapSack(self, val, wt, capacity):
- dp=[[-1]*(capacity+1) for _ in range(len(wt))]
- return fun(capacity,len(val)-1,val,wt,dp)
Advertisement
Add Comment
Please, Sign In to add comment