imashutosh51

Rod Cutting to maximum profit

Mar 6th, 2026 (edited)
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.46 KB | None | 0 0
  1. #User function Template for python3
  2. '''
  3. 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)
  4.  
  5. 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.
  6.  
  7. Base Condition:
  8. 1)if n<0 means all prices you have explored so return 0
  9. 2)cur_size ie. cur_remaining_rod_size becomes <=0 means, nothing remained to cut, so return 0
  10. 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.
  11. '''
  12. def fun(n,rem,price,dp):
  13.     if n<0: #no elements left
  14.         return 0
  15.     if rem<=0:
  16.         return 0
  17.     if dp[n][rem]!=-1:
  18.         return dp[n][rem]
  19.     rod_length=n+1 #price[i] denotes the price of the (i+1) size rod
  20.     take=0
  21.     if rem>=rod_length:
  22.         take=price[n]+fun(n,rem-rod_length,price,dp)
  23.     not_take=fun(n-1,rem,price,dp)
  24.     dp[n][rem]=max(take,not_take)
  25.     return dp[n][rem]
  26.  
  27. class Solution:
  28.     def cutRod(self, price):
  29.         n=len(price)
  30.         dp=[[-1]*(n+1) for _ in range(len(price))]
  31.         #dp[i][j] means: what is the maximum profit obtainable using rod lengths from 1 to i+1
  32.         #to fill a remaining rod length j
  33.         return fun(n-1,n,price,dp)
Advertisement
Add Comment
Please, Sign In to add comment