Skip to content

Commit aafa135

Browse files
committed
Added A greedy problem: Cutting a Rod
1 parent a5b4c09 commit aafa135

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

Greedy/Cutting_a_Rod/CuttingARod.java

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

0 commit comments

Comments
 (0)