Python Program for Cutting a Rod

The Rod Cutting problem is a classic dynamic programming challenge where we cut a rod into pieces to maximize total value. Given a rod of length n and prices for different lengths, we find the optimal way to cut the rod for maximum profit.

Problem Statement

You are given a rod of length n and an array price[] where price[i] represents the price of a rod of length i+1. Your task is to determine the maximum value obtainable by cutting up the rod and selling the pieces.

Using Recursive Approach

The recursive approach tries all possible ways to cut the rod and chooses the one with maximum profit ?

Steps

  • If the rod length becomes 0, return 0
  • Try every possible cut and recursively calculate the total value
  • Return the maximum of all possible values

Example

# Recursive approach to Rod Cutting
def cut_rod_recursive(price, n):
    if n == 0:
        return 0

    max_val = float('-inf')

    # Try every possible cut
    for i in range(n):
        max_val = max(max_val, price[i] + cut_rod_recursive(price, n - i - 1))

    return max_val

# Test input
price = [1, 5, 8, 9, 10, 17, 17, 20]
n = len(price)
result = cut_rod_recursive(price, n)
print(f"Maximum value (Recursive): {result}")
Maximum value (Recursive): 22

Using Dynamic Programming (Bottom-Up)

The recursive method recalculates the same subproblems multiple times. Dynamic programming stores results of subproblems and builds the solution efficiently ?

Steps

  • Create a table dp[] of size n+1 and initialize it to 0
  • Calculate the best value for every rod length from 1 to n
  • For each length, try all cuts and update the maximum value

Example

# Bottom-up DP approach to Rod Cutting
def cut_rod_dp(price, n):
    dp = [0] * (n + 1)

    for i in range(1, n + 1):
        max_val = float('-inf')
        for j in range(i):
            max_val = max(max_val, price[j] + dp[i - j - 1])
        dp[i] = max_val

    return dp[n]

# Test input
price = [1, 5, 8, 9, 10, 17, 17, 20]
n = len(price)
result = cut_rod_dp(price, n)
print(f"Maximum value (DP): {result}")
print(f"Rod length: {n}")
Maximum value (DP): 22
Rod length: 8

Complete Solution with Cut Tracking

Here's an enhanced version that also tracks which cuts to make ?

def cut_rod_with_cuts(price, n):
    dp = [0] * (n + 1)
    cuts = [0] * (n + 1)
    
    for i in range(1, n + 1):
        max_val = float('-inf')
        for j in range(i):
            if price[j] + dp[i - j - 1] > max_val:
                max_val = price[j] + dp[i - j - 1]
                cuts[i] = j + 1  # Store the length of first cut
        dp[i] = max_val
    
    # Reconstruct the cuts
    cut_lengths = []
    remaining = n
    while remaining > 0:
        cut_length = cuts[remaining]
        cut_lengths.append(cut_length)
        remaining -= cut_length
    
    return dp[n], cut_lengths

# Test with the same input
price = [1, 5, 8, 9, 10, 17, 17, 20]
n = len(price)
max_value, optimal_cuts = cut_rod_with_cuts(price, n)

print(f"Maximum value: {max_value}")
print(f"Optimal cuts: {optimal_cuts}")
print(f"Total pieces: {len(optimal_cuts)}")
Maximum value: 22
Optimal cuts: [2, 6]
Total pieces: 2

Comparison

Approach Time Complexity Space Complexity Best For
Recursive O(2^n) O(n) Understanding the problem
Dynamic Programming O(n²) O(n) Efficient solution

Conclusion

The rod cutting problem demonstrates how dynamic programming can optimize exponential recursive solutions. The DP approach reduces time complexity from O(2^n) to O(n²) by storing subproblem results and avoiding redundant calculations.

Updated on: 2026-03-25T06:50:33+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements