Open In App

Rod Cutting Problem in C

Last Updated : 09 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

  1. Define a recursive function that takes the rod length and price array as input.
  2. Base Case: If the rod length is zero, return zero.
  3. Initialize a variable to store the maximum profit.
  4. 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.
  5. 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;
}

Output
Maximum 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

  1. Create a table to store the maximum profit for each rod length initialized to -1.
  2. Base Case: If the rod length is zero, return zero as no profit can be made from a rod of length zero.
  3. 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.
  4. 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.
  5. After computing the maximum profit for the current rod length, store the result in the memoization table to avoid future redundant calculations.
  6. 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;
}

Output
Maximum 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

  1. Create an array to store the maximum profit for each rod length.
  2. Initialize the array with zero for rod length zero.
  3. 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.
  4. 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;
}

Output
Maximum profit is 22

Time Complexity: O(n^2), where n is the rod length.
Auxiliary Space: O(n)


Next Article
Article Tags :

Similar Reads