具体题目和解题如下所示:
'''
管子在不同的长度利润不一样,
比如[1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 33],
长度为1时利润1快,而长度为2时利润5快
给定长度n,求怎么切开卖,利润最大,并把此时方案输出
'''
from collections import defaultdict
from functools import lru_cache
# drd notes: 长1价值1,长2价值5,.... , 长i价值prices[i - 1]; complete_price size = prices len
price_list = [1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 33]
price_dict = defaultdict(int)
for i, p in enumerate(price_list):
price_dict[i + 1] = p
solution = {}
# drd notes: 求长度为n时,进行分切售卖后的最高利润
@lru_cache(maxsize=100)
def calc_max_price(n):
candidates = [(price_dict[n], (n, 0))] + \
[(calc_max_price(i) + calc_max_price(n - i), (i, n - i)) for i in range(1, n)]
max_price, split = max(candidates)
# drd notes: 分隔结果展示
solution[n] = split
return max_price
# drd notes: 在调用calc_max_price后,解析中间结果solution
def print_solution(n):
len1,len2 = solution[n]
if len1 == 0 or len2 == 0:
return [len1 + len2]
else:
return print_solution(len1) + print_solution(len2)
if __name__ == '__main__':
# drd notes: 输出最大利润;
print(calc_max_price(23))
# drd notes:输出最大利润时的一个方案
print(print_solution(23))
# 23时最大利润68,方案:[11, 10, 2]