Constructs a bottom-up dynamic programming solution for the rod-cutting problem Runtime: O(n^2) Arguments --------- * `n`: int, the maximum length of the rod. * `prices`: list, the prices for each piece of rod. ``p[i-i]`` is the price for a rod of length ``i``
(n: int, prices: list)
| 131 | |
| 132 | |
| 133 | def bottom_up_cut_rod(n: int, prices: list): |
| 134 | """ |
| 135 | Constructs a bottom-up dynamic programming solution for the rod-cutting problem |
| 136 | |
| 137 | Runtime: O(n^2) |
| 138 | |
| 139 | Arguments |
| 140 | --------- |
| 141 | |
| 142 | * `n`: int, the maximum length of the rod. |
| 143 | * `prices`: list, the prices for each piece of rod. ``p[i-i]`` is the |
| 144 | price for a rod of length ``i`` |
| 145 | |
| 146 | Returns |
| 147 | ------- |
| 148 | |
| 149 | The maximum revenue obtainable from cutting a rod of length `n` given |
| 150 | the prices for each piece of rod p. |
| 151 | |
| 152 | Examples |
| 153 | -------- |
| 154 | |
| 155 | >>> bottom_up_cut_rod(4, [1, 5, 8, 9]) |
| 156 | 10 |
| 157 | >>> bottom_up_cut_rod(10, [1, 5, 8, 9, 10, 17, 17, 20, 24, 30]) |
| 158 | 30 |
| 159 | """ |
| 160 | _enforce_args(n, prices) |
| 161 | |
| 162 | # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of |
| 163 | # length 0. |
| 164 | max_rev = [float("-inf") for _ in range(n + 1)] |
| 165 | max_rev[0] = 0 |
| 166 | |
| 167 | for i in range(1, n + 1): |
| 168 | max_revenue_i = max_rev[i] |
| 169 | for j in range(1, i + 1): |
| 170 | max_revenue_i = max(max_revenue_i, prices[j - 1] + max_rev[i - j]) |
| 171 | |
| 172 | max_rev[i] = max_revenue_i |
| 173 | |
| 174 | return max_rev[n] |
| 175 | |
| 176 | |
| 177 | def _enforce_args(n: int, prices: list): |