-
-
Notifications
You must be signed in to change notification settings - Fork 51
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
max height ladder possible from given no. of blocks - O(logn)
- Loading branch information
1 parent
5a62b0c
commit c37a067
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package Lecture14; | ||
|
||
public class maxHeightLadder { | ||
|
||
public static void main(String[] args) { | ||
|
||
int totalBlocks = 20; | ||
System.out.println(maxHeight(totalBlocks)); | ||
|
||
System.out.println(maxHeight(21)); | ||
System.out.println(maxHeight(100)); | ||
System.out.println(maxHeight(1)); | ||
System.out.println(maxHeight(0)); | ||
System.out.println(maxHeight(6)); | ||
System.out.println(maxHeight(7)); | ||
} | ||
|
||
// make ladder of maximum height possible with given number of blocks | ||
public static int maxHeight(int n) { | ||
if (n < 1) { | ||
return -1; | ||
} | ||
int temp = n; | ||
int blocks = n * (n + 1) / 2; | ||
|
||
while (blocks > temp) { | ||
n = n / 2; | ||
blocks = n * (n + 1) / 2; | ||
} | ||
if (((n + 1) * (n + 2) / 2) <= temp) { | ||
return n + 1; | ||
} | ||
return n; | ||
} | ||
} |