From c37a0677de9d27e88860a7debd6ad15f9cffb5be Mon Sep 17 00:00:00 2001 From: NirmalSilwal Date: Sun, 30 Aug 2020 05:34:12 +0530 Subject: [PATCH] max height ladder possible from given no. of blocks - O(logn) --- .../Day14/maxHeightLadder.java | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 CodingBlocks Training/Day14/maxHeightLadder.java diff --git a/CodingBlocks Training/Day14/maxHeightLadder.java b/CodingBlocks Training/Day14/maxHeightLadder.java new file mode 100644 index 0000000..f980ee3 --- /dev/null +++ b/CodingBlocks Training/Day14/maxHeightLadder.java @@ -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; + } +}