Python程序:查找切割木棒并销售相同长度木棒后的最大利润


假设我们有一个名为 rodLen 的木棒长度列表。我们还有另外两个整数,称为 profit 和 cost,分别表示每单位长度的利润和每次切割的成本。我们可以每单位长度获得 profit 的利润,但我们只能销售长度都相同的木棒。我们还可以将一根木棒切割成两部分,它们的长度为整数,但我们必须为每次切割支付 cost 的成本。我们可以根据需要切割木棒任意多次。我们需要找到可以获得的最大利润。

因此,如果输入类似于 rodLen = [7, 10] profit = 6 cost = 4,则输出将为 82,因为我们可以将长度为 7 的木棒切割成两根木棒,长度分别为 5 和 2。然后,我们可以将长度为 10 的木棒切割成两根木棒,长度均为 5。然后将所有 3 根长度为 5 的木棒出售,总利润为 (5 + 5 + 5) * 6 - (2*4) = 82。

为了解决这个问题,我们将遵循以下步骤:

  • n := rodLen 的大小
  • 如果 n 等于 0,则
    • 返回 0
  • l_max := rodLen 的最大值
  • p_max := 0
  • 对于 cuts 从 1 到 l_max,执行以下操作:
    • p_cut := 0
    • 对于 rodLen 中的每个 rod_len,执行以下操作:
      • 如果 rod_len < cuts,则
        • 进入下一个迭代
      • c_count := rod_len / cuts
      • total_len := c_count * cuts
      • 如果 rod_len 等于 total_len,则
        • c_count := c_count - 1
      • curr_profit := total_len * profit - cost * c_count
      • 如果 curr_profit < 0,则
        • 进入下一个迭代
      • p_cut := p_cut + curr_profit
    • p_max := p_max 和 p_cut 的最大值
  • 返回 p_max

示例

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

Open Compiler
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 // cuts 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

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

82

更新于: 2021年10月18日

396 次查看

开启你的 职业生涯

完成课程获得认证

开始学习
广告