File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed
CodingBlocks Training/Day14 Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments