Skip to content

Commit 30a066a

Browse files
Solution of Rod cutting problem added
1 parent a1fab7a commit 30a066a

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Rod cutting problem/solution.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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+
}

0 commit comments

Comments
 (0)