forked from Red-0111/Anything-Repo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprintDiagonal.java
41 lines (33 loc) · 997 Bytes
/
printDiagonal.java
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
public class q1 {
static int optCost(int freq[], int i, int j) {
if (j < i)
return 0;
if (j == i)
return freq[i];
int fsum = sum(freq, i, j);
int min = Integer.MAX_VALUE;
for (int r = i; r <= j; ++r) {
int cost = optCost(freq, i, r - 1) +
optCost(freq, r + 1, j);
if (cost < min)
min = cost;
}
return min + fsum;
}
static int optimalSearchTree(int keys[], int freq[], int n) {
return optCost(freq, 0, n - 1);
}
static int sum(int freq[], int i, int j) {
int s = 0;
for (int k = i; k <= j; k++)
s += freq[k];
return s;
}
public static void main(String[] args) {
int keys[] = { 10, 12, 20 };
int freq[] = { 34, 8, 50 };
int n = keys.length;
System.out.println("Cost of Optimal BST is " +
optimalSearchTree(keys, freq, n));
}
}