以两个单独的目标值作为约束条件,求最大组合和



给定一组数字(可以包括重复的数字(,表示汽车制造所需的小时数。还有两个数字,代表两个工厂的工作时间。找出可以生产的独特汽车的最大数量。

测试用例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问题。但我无法解决。有什么想法吗?

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)

用递归函数求解。每次它都试图看看一辆汽车(来自小时阵列(是否可以由一家公司制造。如果可以的话,它会检查剩余的汽车(小时(,看看是否有任何一辆可以制造(儿童(。

最新更新