Skip to content

Commit b00e908

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

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package Lecture14;
2+
3+
// complexity: O(n)
4+
public class maxHeightLadder2 {
5+
6+
public static void main(String[] args) {
7+
8+
int n = 20;
9+
System.out.println(maxHeight(n)); // 5
10+
11+
System.out.println(maxHeight(21)); // 6
12+
System.out.println(maxHeight(100)); // 13
13+
System.out.println(maxHeight(1)); // 1
14+
System.out.println(maxHeight(0)); // -1
15+
System.out.println(maxHeight(6)); // 3
16+
System.out.println(maxHeight(7)); // 3
17+
}
18+
19+
public static int maxHeight(int n) {
20+
if (n < 1) {
21+
return -1;
22+
}
23+
int answer = 0;
24+
for (int height = 1; height <= n; height++) {
25+
int blocksNeeded = height * (height + 1) / 2;
26+
if (blocksNeeded <= n) {
27+
answer = height;
28+
}
29+
}
30+
return answer;
31+
}
32+
}

0 commit comments

Comments
 (0)