You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现4个数组满足米数约束的最大收益组合求解

代码修改方案

核心修改逻辑

  • 你原来的代码只传入了收益数组,没有关联对应的米数,而每个收益的索引i对应的米数就是i+1(因为四个数组的米数都是1~6按顺序排列),所以直接通过索引就能计算米数总和
  • 在四层循环中新增判断:只有四个索引对应的米数总和等于12时,才将该组合的收益总和存入优先队列,不符合条件的组合直接跳过
  • 额外新增了米数组合存储逻辑,方便你查看每一组的具体选值,不需要可以自行删除

修改后完整代码

from queue import PriorityQueue
def KMaxCombinations(A_profit, B_profit, C_profit, D_profit, K):
    # 用负数值模拟最大堆
    pq = PriorityQueue()
    N = len(A_profit)
    # 遍历所有组合
    for i in range(N):
        rice_a = i + 1
        profit_a = A_profit[i]
        for j in range(N):
            rice_b = j + 1
            profit_b = B_profit[j]
            for k in range(N):
                rice_c = k + 1
                profit_c = C_profit[k]
                for l in range(N):
                    rice_d = l + 1
                    profit_d = D_profit[l]
                    # 规则校验:米数总和等于12
                    if rice_a + rice_b + rice_c + rice_d != 12:
                        continue
                    total_profit = profit_a + profit_b + profit_c + profit_d
                    # 存入队列,格式为(负总收益,总收益,对应米数组合)
                    pq.put((-total_profit, total_profit, (rice_a, rice_b, rice_c, rice_d)))
    
    # 输出前K组结果
    count = 0
    while count < K and not pq.empty():
        res = pq.get()
        print(f"第{count+1}组:总收益{res[1]},米数组合(A,B,C,D)为{res[2]}")
        count += 1

# 驱动代码
A = [50.4, 100.8, 201.6, 403.2, 806.4, 1612.8]
B = [40.8, 81.6, 163.2, 326.4, 652.8, 1305.6]
C = [110, 220, 440, 880, 1760, 3520]
D = [64, 128, 256, 512, 1024, 2048]
K = 3

# 函数调用
KMaxCombinations(A, B, C, D, K)

补充说明

  • 你要求的规则1(选中米数在16之间)天然满足,因为四个数组的米数范围都是16,不需要额外加判断
  • 当前总组合数仅为6^4=1296种,数据量极小,暴力遍历完全够用,不需要额外做性能优化

内容的提问来源于stack exchange,提问作者Bobun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 05:36:00