Program to find maximum profit after cutting rods and selling same length rods in Python

Suppose we have a list of rod lengths called rodLen. We also have another two integers called profit and cost, represents profit per length and cost per cut. We can make gain profit per unit length of a rod but we can only sell rods that are all of the same length. We can also cut a rod into two pieces such that their lengths are integers, but we have to pay cost amount for each cut. We can cut a rod as many times as we want. We have to find the maximum profit that we can make.

So, if the input is like rodLen = [7, 10] profit = 6 cost = 4, then the output will be 82, as we can cut the rod of length 7 into two rods, with length 5 and 2. We can then cut the rod of length 10 into two rods, both with length 5. Then sell all 3 rods of length 5 for a total profit of (5 + 5 + 5) * 6 - (2*4) = 82.

To solve this, we will follow these steps −

  • n := size of rodLen
  • if n is same as 0, then
    • return 0
  • l_max := maximum of rodLen
  • p_max := 0
  • for cuts in range 1 to l_max, do
    • p_cut := 0
    • for each rod_len in rodLen, do
      • if rod_len
      • go for next iteration
    • c_count := rod_len / cuts
    • total_len := c_count * cuts
    • if rod_len is same as total_len, then
      • c_count := c_count - 1
    • curr_profit := total_len * profit - cost * c_count
    • if curr_profit
    • go for next iteration
  • p_cut := p_cut + curr_profit
  • p_max := maximum of p_max and p_cut
  • return p_max
  • Example

    Let us see the following implementation to get better understanding −

    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 

    Input

    [7, 10], 6, 4

    Output

    82
    Updated on: 2021-10-18T12:11:39+05:30

    553 Views

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements