The Rod Cutting problem is a classic problem in dynamic programming. Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n, the task is to determine the maximum value obtainable by cutting up the rod and selling the pieces.
In this article, we will learn how to solve rod cutting problem. We will also look at different approaches to solve this problem.
Example:
Input:
Length of the rod (n): 8
Prices for each length: [1, 5, 8, 9, 10, 17, 17, 20]
Output:
Maximum profit is 22.
Explanation:
Cutting the rod into two pieces of length 2 and 6 gives the maximum profit (5 + 17 = 22).
How to Solve the Rod Cutting Problem?
Solving the Rod Cutting problem involves determining the optimal cuts to maximize the profit. There are several methods to achieve this in C.
Method 1: Using Naive Recursive Approach
In this method, we will use a recursive approach to explore all possible ways to cut the rod and calculate the profit for each combination. The idea is to try every possible cut of the rod and recursively solve the subproblem for the remaining part of the rod. This way, we consider all possible ways of cutting the rod and take the maximum profit among them.
Approach
- Define a recursive function that takes the rod length and price array as input.
- Base Case: If the rod length is zero, return zero.
- Initialize a variable to store the maximum profit.
- For each possible cut length from 1 to the rod length:
- Calculate the profit for the current cut and the remaining rod length.
- Update the maximum profit if the current profit is higher.
- Return the maximum profit.
C Program to Solve Rod Cutting Problem using Recursion
The below program demonstrates how we can solve the Rod Cutting problem using a recursive approach in C.
C
//C program to solve rod cutting problem
#include <stdio.h>
// Function to find the maximum profit from cutting a rod of
// length n
int rodCutting(int price[], int n)
{
// Base case: if the rod length is 0, no profit can be
// made
if (n == 0)
return 0;
// Initialize the maximum profit to 0
int maxProfit = 0;
// Iterate through all possible first cut positions
// (from 1 to n)
for (int i = 1; i <= n; i++) {
// Calculate the profit for the current cut
int currentProfit
= price[i - 1] + rodCutting(price, n - i);
// Update the maximum profit if the current profit
// is greater
if (currentProfit > maxProfit) {
maxProfit = currentProfit;
}
}
// Return the maximum profit obtained
return maxProfit;
}
int main()
{
// Array representing the prices of rods of different
// lengths
int price[] = { 1, 5, 8, 9, 10, 17, 17, 20 };
// Calculate the length of the price array
int length = sizeof(price) / sizeof(price[0]);
// Print the maximum profit obtainable from a rod of the
// given length
printf("Maximum profit is %d\n",
rodCutting(price, length));
return 0;
}
OutputMaximum profit is 22
Time Complexity: O(2^n), where n is the rod length.
Auxiliary Space: O(n)
Method 2: Using Dynamic Programming
In this approach, Instead of solving the same subproblem multiple times, we store the results of the solved subproblems in a table. This way, we only solve each subproblem once and use the stored results to build up the solution for larger problems.
Approach
- Create a table to store the maximum profit for each rod length initialized to -1.
- Base Case: If the rod length is zero, return zero as no profit can be made from a rod of length zero.
- Before performing any computation, check if the result for the current rod length is already computed and stored in the table. If it is, return that value directly.
- For each possible cut length from 1 to the rod length, calculate the profit for the current cut plus the profit for the remaining rod length (using the recursive function). Keep track of the maximum profit obtained from these cuts.
- After computing the maximum profit for the current rod length, store the result in the memoization table to avoid future redundant calculations.
- Return the maximum profit.
C Program to Solve Rod Cutting Problem Using Top-Down Dynamic Programming
The below program demonstrates how we can solve the Rod Cutting problem using dynamic programming in C.
C
// C program to solve rod cutting problem
#include <stdio.h>
#include <string.h>
// Function to find the maximum profit using top-down
// dynamic programming
int rodCutting(int price[], int n, int dp[])
{
// Base case: If the length of the rod is 0, profit is 0
if (n == 0)
return 0;
// If the result is already computed, return it
if (dp[n] != -1)
return dp[n];
// Initialize the maximum profit to 0
int maxProfit = 0;
// Iterate over each possible cut position
for (int i = 1; i <= n; i++) {
// Calculate the profit for the current cut
int currentProfit
= price[i - 1] + rodCutting(price, n - i, dp);
// Update the maximum profit if the current profit
// is greater
if (currentProfit > maxProfit) {
maxProfit = currentProfit;
}
}
// Store the computed result in dp array
dp[n] = maxProfit;
return maxProfit;
}
int main()
{
// Array representing the prices of rods of different
// lengths
int price[] = { 1, 5, 8, 9, 10, 17, 17, 20 };
// Calculate the length of the price array
int length = sizeof(price) / sizeof(price[0]);
// Array to store the maximum profit for each length of
// the rod
int dp[length + 1];
// Initialize dp array with -1 indicating that the
// result is not computed
memset(dp, -1, sizeof(dp));
// Print the maximum profit obtainable from a rod of the
// given length
printf("Maximum profit is %d\n",
rodCutting(price, length, dp));
return 0;
}
OutputMaximum profit is 22
Time Complexity: O(n^2), where n is the rod length.
Auxiliary Space: O(n)
Method 3: Using Bottom-Up Approach
The bottom-up approach can be used to iteratively solve for the maximum profit from the smallest subproblems (smallest rod lengths) to the largest subproblems (full rod length), ensuring that all necessary subproblems are solved before they are needed.
Approach
- Create an array to store the maximum profit for each rod length.
- Initialize the array with zero for rod length zero.
- For each rod length from 1 to n:
- For each cut length from 1 to the current rod length:
- Calculate the profit for the current cut and update the array if the profit is higher.
- Return the value in the array for the rod length n.
C Program to Solve Rod Cutting Problem using Bottom-Up Approach
The below program demonstrates how we can solve the Rod Cutting problem using the bottom-up approach in C.
C
// C program to solve rod cutting problem
#include <stdio.h>
// Function to find the maximum profit using the bottom-up
// approach
int rodCutting(int price[], int n)
{
// Array to store the maximum profit for each length of
// the rod
int dp[n + 1];
// Base case: profit is 0 when the rod length is 0
dp[0] = 0;
// Iterate over each possible rod length from 1 to n
for (int i = 1; i <= n; i++) {
// Initialize the maximum profit for the current
// length
int maxProfit = 0;
// Iterate over each possible cut position
for (int j = 1; j <= i; j++) {
// Calculate the profit for the current cut
int currentProfit = price[j - 1] + dp[i - j];
// Update the maximum profit if the current
// profit is greater
if (currentProfit > maxProfit) {
maxProfit = currentProfit;
}
}
// Store the maximum profit for the current length
// in dp array
dp[i] = maxProfit;
}
// Return the maximum profit for the rod of length n
return dp[n];
}
int main()
{
// Array representing the prices of rods of different
// lengths
int price[] = { 1, 5, 8, 9, 10, 17, 17, 20 };
// Calculate the length of the price array
int length = sizeof(price) / sizeof(price[0]);
// Print the maximum profit obtainable from a rod of the
// given length
printf("Maximum profit is %d\n",
rodCutting(price, length));
return 0;
}
OutputMaximum profit is 22
Time Complexity: O(n^2), where n is the rod length.
Auxiliary Space: O(n)
Similar Reads
Rod Cutting Problem in C++
The Rod Cutting Problem is a classic dynamic programming problem where a rod of length N and a list of prices for smaller pieces of rod is given, and the task is to determine the maximum value obtainable by cutting up the rod and selling the pieces. The length of the rod is taken as the size of the
4 min read
strtoumax() function in C++
The strtoumax() function in C++ interprets the contents of a string as an integral number of the specified base and return its value as an uintmax_t(maximum width unsigned integer). This function also sets an end pointer that points to the first character after the last valid numeric character of th
4 min read
sector() function in C
The header file graphics.h contains sector() function which draws and fills an elliptical pie slice with (x, y) as center, (s_angle, e_angle) as starting and ending angle and (x_radius, y_radius) as x and y radius of sector. Syntax : void sector(int x, int y, int s_angle, int e_angle, int x_radius,
2 min read
C program for pipe in Linux
Working and implementation of Pipe in Linux. Prerequisite : Pipe in Linux Approach : Pipe is highly used in Linux. Basically, pipe has 2 parts, one part is for writing and another is used for reading. So, an array of size 2 is taken. a[1] is used for writing and a[0] for reading.After reading from p
1 min read
C Program to count number of lines in a file
C /* C Program to count the Number of Lines in a Text File */ #include <stdio.h> #define MAX_FILE_NAME 100 int main() { FILE *fp; int count = 0; // Line counter (result) char filename[MAX_FILE_NAME]; char c; // To store a character read from file // Get file name from user. The file should be
1 min read
Online Voting System in C
Voting in elections is one of the most fundamental organs of any Democracy and in the modern world, voting is done through digital machines. In this article, we will try to write a simple Online Voting System using C programming language. Features of Online Voting System in CThe online voting system
5 min read
isalnum() function in C Language
isalnum() function in C programming language checks whether the given character is alphanumeric or not. isalnum() function defined in ctype.h header file. Alphanumeric: A character that is either a letter or a number. Syntax: int isalnum(int x); Examples: Input : 1 Output : Entered character is alph
2 min read
Output of C programs | Set 64 (Pointers)
Prerequisite : Pointers in C Question 1 : What will be the output of following program? C #include "stdio.h" int main() { char a[] = { 'A', 'B', 'C', 'D' }; char* ppp = &a[0]; *ppp++; // Line 1 printf("%c %c ", *++ppp, --*ppp); // Line 2 } OPTIONS: a)C B b)B A c)B C d)C AOUTPUT: (d) C AExplanati
3 min read
abs(), labs(), llabs() functions in C/C++
The std::abs(), std::labs() and std::llabs() in C++ are built-in functions that are used to find the absolute value of any number that is given as the argument. Absolute value is the value of a number without any sign. These functions are defined inside the <cmath> header file.In this article,
3 min read
hypot() Function in C
The hypot() function in C is used to find the length of the hypotenuse of a right-angled triangle given the lengths of the other two sides. This function is particularly useful in various fields of science and engineering where distance calculations are required.The function is declared in the <m
2 min read