在Python中切割杆并出售相同长度的杆后找到最大利润的程序

假设我们有一个名为 rodLen 的杆长度列表。我们还有另外两个整数叫做利润和成本,分别代表每长度的利润和每切割的成本。我们可以通过每单位长度的杆获得利润,但我们只能出售长度相同的杆。我们也可以将一根杆切成两段,使它们的长度为整数,但我们必须为每次切割支付成本金额。我们可以根据需要多次切割一根杆。我们必须找到我们可以赚取的最大利润。

因此,如果输入类似于 rodLen = [7, 10] 利润 = 6 成本 = 4,那么输出将是 82,因为我们可以将长度为 7 的杆切割成两根长度为 5 和 2 的杆。然后我们可以将长度为 10 的杆切成两根长度为 5 的杆,然后将长度为 5 的 3 根杆全部卖出,总利润为 (5 + 5 + 5) * 6 - (2*4) = 82。

示例

让我们看看以下实现以获得更好的理解 -

def solve(rodLen, profit, cost):
   n = len(rodLen)
   if n == 0:
      return 0
   l_max = max(rodLen)
   p_max = 0

   for cuts in range(1, l_max + 1):
      p_cut = 0
      for rod_len in rodLen:
         if rod_len < cuts:
            continue
         c_count = rod_len // 削减
         total_len = c_count * cuts
         if rod_len == total_len:
            c_count -= 1
         curr_profit = total_len * profit - cost * c_count
         if curr_profit < 0:
            continue
         p_cut += curr_profit
      p_max = max(p_max, p_cut)
   return p_max

rodLen = [7, 10]
profit = 6
cost = 4
print(solve(rodLen, profit, cost))

输入

[7, 10], 6, 4
输出结果
82

猜你喜欢