0% completed
Solution: Rod Cutting
Problem Statement
Given a rod of length 'n', we are asked to cut the rod and sell the pieces in a way that will maximize the profit. We are also given the price of every piece of length 'i' where '1 <= i <= n'.
Example:
Lengths: [1, 2, 3, 4, 5]
Prices: [2, 6, 7, 10, 13]
Rod Length: 5
Let's try different combinations of cutting the rod:
Five pieces of length 1 => 10 price
Two pieces of length 2 and one piece of length 1 => 14 price
One piece of length 3 and two pieces of length 1 => 11 price
One piece of length 3 and one piece of length 2 => 13 price
.....
.....
.....
Anonymous
· 2 years ago
class Solution: def solveRodCutting(self, lengths, prices, n): def dp(index, acc, length, memo): if (index, acc, length) in memo: return memo[(index, acc, length)] if index == len(lengths): return acc result = 0 if length + lengths[index] <= n: with_item = dp(index, acc + prices[index], length + lengths[index], memo) without_item = dp(index + 1, acc, length, memo) result = max(with_item, without_item) else: result = dp(index + 1, acc, length, memo) # without item // skipping memo[(index, acc, length)] = result return result return dp(0, 0, 0, {})
Anonymous
· 4 years ago
It makes sense to skip the brute force and top down. But it is still useful to provide both of the implementations (no deep dive required). This prevents users from having to search online to find them.
Users can then try each approach and build up to bottom up.
Reading Progress
0%