dp[i] represents the maximum revenue obtainable from a rod of length i. For each length, we try all possible first cuts and take the maximum.
- Create
dparray of sizen + 1, initialized to 0. - For each length
ifrom 1 to n:- For each cut length
jfrom 1 to i:dp[i] = max(dp[i], price[j-1] + dp[i-j]).
- For each cut length
- Return
dp[n].
- Time Complexity: O(N^2).
- Space Complexity: O(N).
def rod_cutting(price, n):
dp = [0] * (n + 1)
for i in range(1, n + 1):
for j in range(1, i + 1):
dp[i] = max(dp[i], price[j - 1] + dp[i - j])
return dp[n]