Skip to content

Commit ad83388

Browse files
committed
🔪 Cutting a Rod
1 parent 7df387a commit ad83388

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Given a rod of length n inches and an array of prices
3+
* that contains prices of all pieces of size smaller than n.
4+
* Determine the maximum value obtainable by cutting up the rod
5+
* and selling the pieces.
6+
*
7+
* Time Complexity : O(n^2)
8+
* which is much better than the
9+
* worst case time complexity of Naive Recursive implementation.
10+
*/
11+
12+
import java.util.*;
13+
import java.io.*;
14+
15+
class CuttingARod {
16+
17+
public static int cutCutCut(int price[], int size) {
18+
19+
int memory[] = new int[size+1];
20+
memory[0] = 0;
21+
22+
for(int i=1; i<=size; i++){
23+
int maximum = Integer.MIN_VALUE;
24+
for(int j=0; j<i; j++) {
25+
maximum = Math.max(maximum, price[j]+memory[i-j-1]);
26+
}
27+
memory[i] = maximum;
28+
}
29+
return memory[size];
30+
}
31+
32+
public static void main(String[] args) {
33+
int price[] = new int[] {1, 5, 8, 9, 10, 17, 17, 20};
34+
int size = price.length;
35+
System.out.println("Maximum Profit: " +
36+
cutCutCut(price, size));
37+
}
38+
}

0 commit comments

Comments
 (0)