Rod Cutting Algorithm

The Rod Cutting Algorithm is a classic dynamic programming problem that focuses on optimizing the process of cutting a rod into smaller pieces in order to maximize the profit obtained from selling those pieces. The problem is typically framed as follows: given a rod of a certain length and a list of prices for different lengths of rod pieces, determine the best way to cut the rod into smaller pieces such that the sum of the prices of those pieces is maximized. The algorithm generally assumes that there is no cost associated with making the cuts and that the rod can be divided into any number of pieces of varying lengths. To solve this problem, the Rod Cutting Algorithm employs dynamic programming techniques, specifically using memoization or tabulation to store results of subproblems, which are then reused in solving larger problems. The algorithm starts by breaking down the problem into smaller subproblems, where each subproblem represents the optimal profit that can be obtained for a rod of a specific length. These subproblems are solved iteratively, and the results are stored in a table or memoization data structure. The optimal solution for the original problem can then be constructed from the solutions of these subproblems. This approach ensures that overlapping subproblems are solved only once, which significantly reduces the time complexity of the algorithm compared to a naive recursive approach.
package DynamicProgramming;

/**
 * A DynamicProgramming solution for Rod cutting problem
 * Returns the best obtainable price for a rod of
 * length n and price[] as prices of different pieces
 */
public class RodCutting {

    private static int cutRod(int[] price, int n) {
        int val[] = new int[n + 1];
        val[0] = 0;

        for (int i = 1; i <= n; i++) {
            int max_val = Integer.MIN_VALUE;
            for (int j = 0; j < i; j++)
                max_val = Math.max(max_val, price[j] + val[i - j - 1]);

            val[i] = max_val;
        }

        return val[n];
    }

    // main function to test
    public static void main(String args[]) {
        int[] arr = new int[]{2, 5, 13, 19, 20};
        int size = arr.length;
	int result = cutRod(arr,size); 
        System.out.println("Maximum Obtainable Value is " +
                result);
    }
}

LANGUAGE:

DARK MODE: