Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #User function Template for python3
- '''
- Unbounded Knapsack because either you can choose an element or not choose but if you are choosing, you can choose multiple times same elment so if choosing-> fun(again on same n) else fun(n-1)
- dp table's rows denotes all the prices of the rod sizes(0->len(prices)-1) and column denotes the n size rod that we have to cut ie n.
- Base Condition:
- 1)if n<0 means all prices you have explored so return 0
- 2)cur_size ie. cur_remaining_rod_size becomes <=0 means, nothing remained to cut, so return 0
- 3)if you are having i which denotes the ith index of prices array, which means price[i]=price of (i+1) size array so when you going to choose a rod_size or cut_size then check that remaining rod size ie. cur_size>= rod_size(i+1) or not.
- '''
- def fun(n,rem,price,dp):
- if n<0: #no elements left
- return 0
- if rem<=0:
- return 0
- if dp[n][rem]!=-1:
- return dp[n][rem]
- rod_length=n+1 #price[i] denotes the price of the (i+1) size rod
- take=0
- if rem>=rod_length:
- take=price[n]+fun(n,rem-rod_length,price,dp)
- not_take=fun(n-1,rem,price,dp)
- dp[n][rem]=max(take,not_take)
- return dp[n][rem]
- class Solution:
- def cutRod(self, price):
- n=len(price)
- dp=[[-1]*(n+1) for _ in range(len(price))]
- #dp[i][j] means: what is the maximum profit obtainable using rod lengths from 1 to i+1
- #to fill a remaining rod length j
- return fun(n-1,n,price,dp)
Advertisement
Add Comment
Please, Sign In to add comment