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