给定一系列数字(可以包括重复数字)--表示汽车制造所需的时间。两个数字,代表两个工厂工作的时间。找出最大数量的独特汽车,可以生产。
测试用例1: 6,5,5,4,3和8,9最大组合为4.5和3与8之和,5和4为和9。
测试用例2: 5,5,6和8,8最大的组合是2。工作8小时的工厂最多能完成一辆需要5小时的车辆,而工作9小时的工厂最多能完成6小时的车辆。
我相信我问的这个问题类似于Leetcode上的组合和II问题。但我解决不了。有什么想法吗?
发布于 2022-10-01 07:15:16
hours = [6, 5, 5, 4, 3]
com_a = 8
com_b = 9
def get_max(hours, com_a, com_b):
if len(hours) == 0: return 0
max_cars_produced = 0
# the order of hours matters, so we check which order provides the highest number
for i in range(len(hours)):
h = hours[i]
child_1 = 0
child_2 = 0
# the order by which the companies are filled also matters
# case I: where first company is filled first
if h <= com_a: child_1 = get_max(hours[i+1:], com_a - h, com_b)
elif h <= com_b: child_1 = get_max(hours[i+1:], com_a, com_b -h)
# case 2: where second company is filled first
if h <= com_b: child_2 = get_max(hours[i+1:], com_a, com_b -h)
elif h <= com_a: child_2 = get_max(hours[i+1:], com_a - h, com_b)
if h <= com_a or h <= com_b:
# if this satisfy this condition, it means that at least one car has been manufactured
num_cars = max(child_1, child_2) + 1
if num_cars > max_cars_produced: max_cars_produced = num_cars
return max_cars_produced
get_max(hours, com_a, com_b)它用递归函数求解。每次它试图看一辆汽车(从小时排列)是否可以由一家公司制造。如果可以的话,它会检查剩下的汽车(小时),看看是否可以制造(儿童)。
https://stackoverflow.com/questions/73916183
复制相似问题