|
1 |
| -/* A Dynamic Programming solution for Rod cutting problem |
2 |
| - Returns the best obtainable price for a rod of |
3 |
| - length n and price[] as prices of different pieces */ |
4 |
| - |
| 1 | +/** |
| 2 | + * A Dynamic Programming solution for Rod cutting problem |
| 3 | + * Returns the best obtainable price for a rod of |
| 4 | + * length n and price[] as prices of different pieces |
| 5 | + * |
| 6 | + */ |
5 | 7 | public class RodCutting {
|
6 |
| - |
7 |
| - private static int cutRod(int price[],int n) |
8 |
| - { |
9 |
| - int val[] = new int[n+1]; |
10 |
| - val[0] = 0; |
11 | 8 |
|
12 |
| - for (int i = 1; i<=n; i++) |
13 |
| - { |
14 |
| - int max_val = Integer.MIN_VALUE; |
15 |
| - for (int j = 0; j < i; j++) |
16 |
| - max_val = Math.max(max_val,price[j] + val[i-j-1]); |
17 |
| - |
18 |
| - val[i] = max_val; |
19 |
| - } |
| 9 | + private static int cutRod(int[] price, int n) { |
| 10 | + int val[] = new int[n + 1]; |
| 11 | + val[0] = 0; |
| 12 | + |
| 13 | + for (int i = 1; i <= n; i++) { |
| 14 | + int max_val = Integer.MIN_VALUE; |
| 15 | + for (int j = 0; j < i; j++) |
| 16 | + max_val = Math.max(max_val, price[j] + val[i - j - 1]); |
| 17 | + |
| 18 | + val[i] = max_val; |
| 19 | + } |
20 | 20 |
|
21 |
| - return val[n]; |
22 |
| - } |
| 21 | + return val[n]; |
| 22 | + } |
23 | 23 |
|
24 |
| - //main function to test |
25 |
| - public static void main(String args[]) |
26 |
| - { |
27 |
| - int arr[] = new int[] {2, 5, 13, 19, 20}; |
28 |
| - int size = arr.length; |
29 |
| - System.out.println("Maximum Obtainable Value is " + |
30 |
| - cutRod(arr, size)); |
31 |
| - } |
| 24 | + // main function to test |
| 25 | + public static void main(String args[]) { |
| 26 | + int[] arr = new int[]{2, 5, 13, 19, 20}; |
| 27 | + int size = arr.length; |
| 28 | + System.out.println("Maximum Obtainable Value is " + |
| 29 | + cutRod(arr, size)); |
| 30 | + } |
32 | 31 | }
|
0 commit comments