首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用两个独立的目标值寻找最大组合和作为约束

用两个独立的目标值寻找最大组合和作为约束
EN

Stack Overflow用户
提问于 2022-10-01 06:08:22
回答 1查看 78关注 0票数 0

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-01 07:15:16

代码语言:javascript
复制
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)

它用递归函数求解。每次它试图看一辆汽车(从小时排列)是否可以由一家公司制造。如果可以的话,它会检查剩下的汽车(小时),看看是否可以制造(儿童)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73916183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档