-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathMaxHeaps.java
More file actions
88 lines (63 loc) · 1.83 KB
/
MaxHeaps.java
File metadata and controls
88 lines (63 loc) · 1.83 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package HashMaps;
import java.util.HashMap;
import java.util.Map;
/**
* Author - archit.s
* Date - 04/11/18
* Time - 12:11 PM
*/
public class MaxHeaps {
long MOD = 1000000007l;
Map<Integer, Long> numberOfHeaps = new HashMap<>();
long[][] nck = new long[101][101];
int[] pow2 = new int[11];
public int solve(int A) {
for(int i=0;i<101;i++){
nck[i][0] = 1l;
nck[i][i] = 1l;
}
for(int i=2;i<101;i++){
for(int j=1;j<i;j++){
nck[i][j] = (nck[i-1][j-1] + nck[i-1][j])%MOD;
}
}
pow2[0] = 1;
for(int i=1;i<11;i++){
pow2[i] = 2*pow2[i-1];
}
numberOfHeaps.put(0,1l);
numberOfHeaps.put(1,1l);
numberOfHeaps.put(2,1l);
numberOfHeaps.put(3,2l);
numberOfHeaps.put(4,3l);
return (int)(solveHeaps(A));
}
int findHeight(int n){
int h = 0;
while(n>0){
n/=2;
h++;
}
return h;
}
int leftTreeElements(int n){
int h = findHeight(n);
//Second last level elements plus rest elements in last level, max upto half filled as its left tree
int r = (pow2[h-2]-1) + Math.min((n-(pow2[h-1]-1)), pow2[h-2] );
return r;
}
public long solveHeaps(int n){
if(numberOfHeaps.containsKey(n)){
return (numberOfHeaps.get(n));
}
int leftTreeElements = leftTreeElements(n);
long solution = (nck[n-1][leftTreeElements]%MOD);
solution = (solution*solveHeaps(leftTreeElements)%MOD);
solution = (solution * solveHeaps(n-1-leftTreeElements))%MOD;
numberOfHeaps.put(n,solution);
return solution;
}
public static void main(String[] args) {
System.out.println(new MaxHeaps().solve(4));
}
}