|
1 |
| -// A Dynamic programming solution for Rod Cutting problem |
| 1 | +// A Dynamic programming solution for Rod Cutting problem |
2 | 2 |
|
3 | 3 | import java.util.*;
|
4 | 4 | import java.lang.*;
|
5 | 5 | import java.io.*;
|
6 | 6 |
|
7 | 7 | class RodCutting
|
8 |
| -{ //a fxn for calculating max of two nos. |
| 8 | +{ |
| 9 | + // A function for calculating max of two nos. |
9 | 10 | static int max(int a,int b)
|
10 |
| - { |
11 |
| - return(a > b) ? a : b ; |
12 |
| - |
13 |
| - } |
14 |
| - |
15 |
| - // returns the max obtainable cost |
16 |
| - static int CutRod(int cost[],int n) |
17 |
| - { int []val=new int[n+1]; |
18 |
| - int i,j; |
19 |
| - val[0]=0; |
20 |
| - |
21 |
| - for(i=1;i<=n;i++) |
22 |
| - { int max_value=Integer.MIN_VALUE; |
23 |
| - for(j=0;j<i;j++) |
24 |
| - max_value=max(max_value,cost[j]+val[i-j-1]); |
25 |
| - val[i]=max_value; |
26 |
| - } |
27 |
| - |
28 |
| - return val[n]; |
29 |
| - } |
30 |
| - |
31 |
| - // driver fxn |
32 |
| - |
33 |
| - public static void main(String args[]) |
34 |
| - { int []arr=new int [] {3,5,8,9,10,17,17,20}; |
35 |
| - int size=arr.length; |
36 |
| - System.out.println("Maximum value is " + CutRod(arr,size)); |
37 |
| - } |
38 |
| -} |
39 |
| - |
40 |
| - |
41 |
| -/*OUTPUT |
42 |
| -Maximum value is 24 */ |
43 |
| - |
44 |
| - |
45 |
| - |
46 |
| - |
47 |
| - |
| 11 | + { |
| 12 | + return (a > b) ? a : b; |
| 13 | + } |
| 14 | + |
| 15 | + // Returns the max obtainable cost |
| 16 | + static int CutRod(int cost[],int n) |
| 17 | + { |
| 18 | + int []val = new int[n+1]; |
| 19 | + int i,j; |
| 20 | + val[0] = 0; |
| 21 | + |
| 22 | + for(i = 1; i <= n; i++) |
| 23 | + { |
| 24 | + int max_value = Integer.MIN_VALUE; |
| 25 | + for(j = 0; j < i; j++) |
| 26 | + max_value = max(max_value, cost[j] + val[i-j-1]); |
| 27 | + val[i] = max_value; |
| 28 | + } |
| 29 | + |
| 30 | + return val[n]; |
| 31 | + } |
| 32 | + |
| 33 | + // Driver function |
| 34 | + |
| 35 | + public static void main(String args[]) |
| 36 | + { |
| 37 | + int []arr = new int [] {3, 5, 8, 9, 10, 17, 17, 20}; |
| 38 | + int size = arr.length; |
| 39 | + System.out.println("Maximum value is " + CutRod(arr, size)); |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | + |
| 44 | +/* OUTPUT |
| 45 | +
|
| 46 | +Maximum value is 24 |
| 47 | +
|
| 48 | +*/ |
0 commit comments