Skip to content

Commit c37a067

Browse files
committed
max height ladder possible from given no. of blocks - O(logn)
1 parent 5a62b0c commit c37a067

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package Lecture14;
2+
3+
public class maxHeightLadder {
4+
5+
public static void main(String[] args) {
6+
7+
int totalBlocks = 20;
8+
System.out.println(maxHeight(totalBlocks));
9+
10+
System.out.println(maxHeight(21));
11+
System.out.println(maxHeight(100));
12+
System.out.println(maxHeight(1));
13+
System.out.println(maxHeight(0));
14+
System.out.println(maxHeight(6));
15+
System.out.println(maxHeight(7));
16+
}
17+
18+
// make ladder of maximum height possible with given number of blocks
19+
public static int maxHeight(int n) {
20+
if (n < 1) {
21+
return -1;
22+
}
23+
int temp = n;
24+
int blocks = n * (n + 1) / 2;
25+
26+
while (blocks > temp) {
27+
n = n / 2;
28+
blocks = n * (n + 1) / 2;
29+
}
30+
if (((n + 1) * (n + 2) / 2) <= temp) {
31+
return n + 1;
32+
}
33+
return n;
34+
}
35+
}

0 commit comments

Comments
 (0)