File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ class rod_cutting
2
+ {
3
+ static int cut_rod (int price [], int n )
4
+ {
5
+ // Declaring a 2D array, T
6
+ int T [][] = new int [n -1 ][n +1 ];
7
+
8
+ // Initializing the array to all zeros
9
+ for (int i =0 ; i < n -1 ; i ++)
10
+ {
11
+ for (int j =0 ; j < n +1 ; j ++ )
12
+ {
13
+ T [i ][j ] = 0 ;
14
+ }
15
+ }
16
+
17
+ for (int i =0 ; i < n -1 ; i ++)
18
+ {
19
+ for (int j =0 ; j < n +1 ; j ++ )
20
+ {
21
+ // First column => 0 length of rod => 0 profit
22
+ if (j == 0 ) {
23
+ continue ;
24
+ }
25
+
26
+ // First row => T[i-1][j] doesn't exist so just pick the second value
27
+ else if (i == 0 ) {
28
+ T [i ][j ] = price [i ] + T [i ][j -i -1 ];
29
+ }
30
+
31
+ // where j <= i => T[i][j-i-1] doesn't exist so just pick the first value
32
+ else if (j -i -1 < 0 ) {
33
+ T [i ][j ] = T [i -1 ][j ];
34
+ }
35
+
36
+ // using the whole expression
37
+ else {
38
+ T [i ][j ] = Math .max (T [i -1 ][j ], (price [i ] + T [i ][j -i -1 ]));
39
+ }
40
+ }
41
+ }
42
+ return T [n -2 ][n ];
43
+ }
44
+
45
+ public static void main (String args [])
46
+ {
47
+ int price [] = new int [] {2 ,5 ,7 ,8 };
48
+ int n = 5 ;
49
+ System .out .println ("Maximum profit is " + cut_rod (price , n ));
50
+ }
51
+ }
You can’t perform that action at this time.
0 commit comments