-
Notifications
You must be signed in to change notification settings - Fork 376
Expand file tree
/
Copy pathRodCutting.java
More file actions
72 lines (67 loc) · 1.48 KB
/
RodCutting.java
File metadata and controls
72 lines (67 loc) · 1.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package DP;
public class RodCutting {
public static void main(String[] args) {
int[] price = { 0, 1, 5, 8, 9, 10, 17, 17, 20 };
System.out.println(RodCutRecusrion(price, price.length - 1));
System.out.println(RCTD(price, price.length - 1, new int[price.length]));
System.out.println(RodCutBU(price));
}
public static int RodCutRecusrion(int[] price, int n) {
int max = price[n];
int left = 1;
int right = n - 1;
while (left <= right) {
int fp = RodCutRecusrion(price, left);
int sp = RodCutRecusrion(price, right);
int total = fp + sp;
if (total > max) {
max = total;
}
left++;
right--;
}
return max;
}
public static int RCTD(int[] price, int n, int[] strg) {
if (strg[n] != 0) {
return strg[n];
}
int max = price[n];
int left = 1;
int right = n - 1;
while (left <= right) {
int fp = RCTD(price, left, strg);
int sp = RCTD(price, right, strg);
int total = fp + sp;
if (total > max) {
max = total;
}
left++;
right--;
}
strg[n] = max;
return max;
}
public static int RodCutBU(int[] price) {
int[] strg = new int[price.length];
strg[0] = price[0];
strg[1] = price[1];
for (int n = 2; n < strg.length; n++) {
int max = price[n];
int left = 1;
int right = n - 1;
while (left <= right) {
int fp = strg[left];
int sp = strg[right];
int total = fp + sp;
if (total > max) {
max = total;
}
left++;
right--;
}
strg[n] = max;
}
return strg[strg.length - 1];
}
}