|
1 | 1 | package com.thealgorithms.dynamicprogramming;
|
2 | 2 |
|
3 | 3 | /**
|
4 |
| - * A DynamicProgramming solution for Rod cutting problem Returns the best |
5 |
| - * obtainable price for a rod of length n and price[] as prices of different |
6 |
| - * pieces |
| 4 | + * A Dynamic Programming solution for the Rod cutting problem. |
| 5 | + * Returns the best obtainable price for a rod of length n and price[] as prices of different pieces. |
7 | 6 | */
|
8 | 7 | public class RodCutting {
|
9 | 8 |
|
10 |
| - private static int cutRod(int[] price, int n) { |
| 9 | + /** |
| 10 | + * This method calculates the maximum obtainable value for cutting a rod of length n |
| 11 | + * into different pieces, given the prices for each possible piece length. |
| 12 | + * |
| 13 | + * @param price An array representing the prices of different pieces, where price[i-1] |
| 14 | + * represents the price of a piece of length i. |
| 15 | + * @param n The length of the rod to be cut. |
| 16 | + * @return The maximum obtainable value. |
| 17 | + */ |
| 18 | + public static int cutRod(int[] price, int n) { |
| 19 | + // Create an array to store the maximum obtainable values for each rod length. |
11 | 20 | int[] val = new int[n + 1];
|
12 | 21 | val[0] = 0;
|
13 | 22 |
|
| 23 | + // Calculate the maximum value for each rod length from 1 to n. |
14 | 24 | for (int i = 1; i <= n; i++) {
|
15 |
| - int max_val = Integer.MIN_VALUE; |
16 |
| - for (int j = 0; j < i; j++) { |
17 |
| - max_val = Math.max(max_val, price[j] + val[i - j - 1]); |
| 25 | + int maxVal = Integer.MIN_VALUE; |
| 26 | + // Try all possible ways to cut the rod and find the maximum value. |
| 27 | + for (int j = 1; j <= i; j++) { |
| 28 | + maxVal = Math.max(maxVal, price[j - 1] + val[i - j]); |
18 | 29 | }
|
19 |
| - |
20 |
| - val[i] = max_val; |
| 30 | + // Store the maximum value for the current rod length. |
| 31 | + val[i] = maxVal; |
21 | 32 | }
|
22 | 33 |
|
| 34 | + // The final element of 'val' contains the maximum obtainable value for a rod of length 'n'. |
23 | 35 | return val[n];
|
24 | 36 | }
|
25 |
| - |
26 |
| - // main function to test |
27 |
| - public static void main(String[] args) { |
28 |
| - int[] arr = new int[] {2, 5, 13, 19, 20}; |
29 |
| - int result = cutRod(arr, arr.length); |
30 |
| - System.out.println("Maximum Obtainable Value is " + result); |
31 |
| - } |
32 | 37 | }
|
0 commit comments