Skip to content

Commit 6c3c02c

Browse files
committed
max height ladder possible using binary search - O(logn)
1 parent b00e908 commit 6c3c02c

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 maxHeightLadder3 {
4+
5+
public static void main(String[] args) {
6+
7+
int n = 20;
8+
System.out.println(maxHeight(n)); // 5
9+
10+
System.out.println(maxHeight(21)); // 6
11+
System.out.println(maxHeight(100)); // 13
12+
System.out.println(maxHeight(1)); // 1
13+
System.out.println(maxHeight(0)); // -1
14+
System.out.println(maxHeight(6)); // 3
15+
System.out.println(maxHeight(7)); // 3
16+
}
17+
18+
public static int maxHeight(int n) {
19+
if (n < 1) {
20+
return -1;
21+
}
22+
int left = 0, right = n, ans = -1;
23+
while (left <= right) {
24+
int height = (left + right) / 2;
25+
int blocksNeeded = height * (height + 1) / 2;
26+
if (blocksNeeded > n) {
27+
right = height - 1;
28+
} else {
29+
ans = height;
30+
left = height + 1;
31+
}
32+
}
33+
return ans;
34+
}
35+
}

0 commit comments

Comments
 (0)