|
| 1 | + |
| 2 | +import time |
| 3 | +from typing import List |
| 4 | + |
| 5 | +memo = {} |
| 6 | + |
| 7 | +def modifiedRodCut(n: int, prices: List[int], costs: List[int], ind = 0) -> int: |
| 8 | + """ |
| 9 | + Modified rod cut algorithm |
| 10 | +
|
| 11 | + Args: |
| 12 | + n (int): The rod length |
| 13 | + costs (List[int]): The array of costs |
| 14 | +
|
| 15 | + Returns: |
| 16 | + int: The maximum revenue from cutting rod of length n |
| 17 | + """ |
| 18 | + if ind == n: |
| 19 | + memo[ind] = prices[n] |
| 20 | + return prices[n] |
| 21 | + return max(prices[ind] - costs[ind], modifiedRodCut(n - (ind + 1), prices, costs, ind + 1)) |
| 22 | + |
| 23 | + |
| 24 | +max_price_memo = {} |
| 25 | +def max_rod_price(n_len: int, prices: List[int]) -> int: |
| 26 | + max_price = prices[n_len] |
| 27 | + if n_len in max_price_memo: |
| 28 | + return max_price_memo[n_len] |
| 29 | + if n_len <= 1: |
| 30 | + max_price_memo[n_len] = prices[n_len] |
| 31 | + return prices[n_len] |
| 32 | + for i in range(1, n_len): |
| 33 | + max_price = max(max_price, max_rod_price(i, prices) + max_rod_price(n_len - i, prices)) |
| 34 | + max_price_memo[n_len] = max_price |
| 35 | + return max_price |
| 36 | + |
| 37 | +def text_cut_rod(n, text_prices): |
| 38 | + if n == 0: |
| 39 | + return 0 |
| 40 | + q = float('-inf') |
| 41 | + for i in range(1, n + 1): |
| 42 | + q = max(q, text_prices[i] + text_cut_rod(n - i, text_prices)) |
| 43 | + return q |
| 44 | + |
| 45 | +### Problem 1 |
| 46 | +cost_memo = {} |
| 47 | +def max_rod_price_cost(n_len: int, prices: List[int], cost: int) -> int: |
| 48 | + if n_len == 0: |
| 49 | + return 0 |
| 50 | + if (n_len - 1) in cost_memo: |
| 51 | + return cost_memo[n_len - 1] |
| 52 | + max_cost = prices[n_len - 1] - cost |
| 53 | + for i in range(1, n_len): |
| 54 | + max_cost = max(max_cost, prices[n_len - 1], (prices[i] + max_rod_price_cost(n_len - i, prices, cost)) - cost) |
| 55 | + cost_memo[n_len] = max_cost |
| 56 | + return max_cost |
| 57 | +### Problem 1 |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == '__main__': |
| 61 | + PRICES = [1, 2, 4, 5, 6, 4, 7, 2, 5, 5] |
| 62 | + print(max_rod_price_cost(9, PRICES, 2)) |
| 63 | + |
| 64 | + |
| 65 | + |
0 commit comments