Cut Rod Algorithm

The Cut Rod Algorithm is a classic optimization problem in computer science and mathematics, which is often approached using dynamic programming techniques. The problem involves a given rod of a certain length and a set of different lengths into which it can be cut. Each possible cut has an associated price, and the goal is to determine the maximum revenue that can be obtained by cutting the rod into smaller pieces and selling them individually. Essentially, the challenge is to find the optimal combination of cuts that maximizes the total value. There are several ways to solve the Cut Rod Algorithm, including recursive methods and dynamic programming approaches, such as top-down memoization and bottom-up methods. The recursive approach involves breaking the problem down into smaller subproblems and solving them individually, while memoization stores the results of these subproblems to avoid redundant calculations. The bottom-up method constructs a solution by iteratively solving smaller subproblems and using their results to build up to the overall solution. As a result, dynamic programming techniques tend to be more efficient than simple recursion, particularly for large input sizes, as they exploit the problem's inherent overlapping subproblems and optimal substructure properties.
/*Given a rod of length n inches and an array of prices that 
contains prices of all pieces of size smaller than n. Determine 
the maximum value obtainable by cutting up the rod and selling 
the pieces.*/

#include <iostream>
using namespace std;
int cutrod(int p[], int n)
{
    int r[n + 1];
    r[0] = 0;
    for (int j = 0; j < n; j++)
    {
        int q = INT_MIN;
        for (int i = 0; i <= j; i++)
        {
            q = max(q, p[i] + r[j - i]);
        }
        r[j + 1] = q;
    }
    return r[n];
}
int main()
{
    int price[] = {1, 5, 8, 9, 10, 17, 17, 20, 24, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50};
    cout << cutrod(price, 30);
    return 0;
}

LANGUAGE:

DARK MODE: