Skip to content

Commit c527dff

Browse files
authored
Add Javadoc comments (TheAlgorithms#4745)
1 parent 574138c commit c527dff

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed
Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,37 @@
11
package com.thealgorithms.dynamicprogramming;
22

33
/**
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.
76
*/
87
public class RodCutting {
98

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.
1120
int[] val = new int[n + 1];
1221
val[0] = 0;
1322

23+
// Calculate the maximum value for each rod length from 1 to n.
1424
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]);
1829
}
19-
20-
val[i] = max_val;
30+
// Store the maximum value for the current rod length.
31+
val[i] = maxVal;
2132
}
2233

34+
// The final element of 'val' contains the maximum obtainable value for a rod of length 'n'.
2335
return val[n];
2436
}
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-
}
3237
}

0 commit comments

Comments
 (0)