Log In Sign Up
Day 38

Day 38 - Extra Work: Rod Cutting Problem

38/60 Days

Rod Cutting Problem #

Welcome to an extra lesson for Day 38 of our 60 Days of Coding Algorithm Challenge! In this additional content, we’ll explore the Rod Cutting Problem, another classic example of dynamic programming.

What is the Rod Cutting Problem? #

The Rod Cutting Problem is an optimization problem where we need to cut a rod of length n into smaller pieces to maximize the total value. Each piece has a value associated with its length, and we need to determine the most profitable way to cut the rod.

Problem Statement #

Given a rod of length n inches and a table of prices pi for i = 1, 2, …, n, determine the maximum revenue rn obtainable by cutting up the rod and selling the pieces.

Naive Recursive Approach #

Let’s start with a naive recursive implementation:

 1def cut_rod_recursive(prices, n):
 2    if n <= 0:
 3        return 0
 4    max_value = float('-inf')
 5    for i in range(n):
 6        max_value = max(max_value, prices[i] + cut_rod_recursive(prices, n - i - 1))
 7    return max_value
 8
 9# Example usage
10prices = [1, 5, 8, 9, 10, 17, 17, 20]
11rod_length = 8
12print(f"Maximum value: {cut_rod_recursive( …