![]() |
VOOZH | about |
Given an array heights[] of size N, where heights[i] is the height of the ith tower. We are standing at the 0th tower with B blocks and L ladders and we have to reach the furthest tower possible by jumping on adjacent towers. For ith tower,
Find the farthest tower we can reach using at most B blocks and L ladders.
Note: A Ladder or Block once used cannot be used again.
Examples:
Input: N=9, heights = [4, 12, 2, 7, 3, 18, 20, 3, 19], B= 10, L= 2
Output: 7
Explanation:
- Start at tower 0.
- Move to tower 1 using your first ladder since 4 < 12.
- Move to tower 2 without using blocks nor ladders because 12 > 2.
- Move to tower 3 using 5 blocks since 2 <= 7.
- Move to tower 4 without using ladders nor blocks since 7 >= 3.
- Move to tower 5 using your second ladder because 3 < 18.
- Move to tower 6 using 2 blocks because 18 < 20.
- Move to tower 7 without using blocks nor ladders because 20 > 3.
- It is impossible to go beyond tower 7 because you do not have any more sufficient blocks or ladders.
Input: N=7, heights = [4, 2, 7, 6, 9, 14, 12], B= 5, L = 1
Output: 4
Explanation:
- Starting at tower 0.
- Go to tower 1 without using ladders nor blocks since 4 >= 2.
- Go to tower 2 using 5 blocks. You must use either blocks or ladders because 2 < 7.
- Go to tower 3 without using ladders nor blocks since 7 >= 6.
- Go to tower 4 using your only ladder. You must use either blocks or ladders because 6 < 9.
It is impossible to go beyond tower 4 because you do not have any more blocks or ladders.
Algorithm: The problem can be solved using the following algorithm:
The problem can be solved using Greedy Approach. Initially, use blocks to climb up the towers. When we run out of blocks, if the find the maximum difference of heights where we have used blocks and then use a ladder for that distance to get extra blocks. To keep track of how many blocks we've used at each step, we use a priority queue to store the differences of heights where we have used blocks.
To simplify things, we ensure that we always have enough blocks by continuously using ladder instead of blocks for the largest jump encountered so far. If, at any point, we don't have enough blocks, we use a ladder and adjust accordingly.
Steps to solve the problem:
Implementation:
7
Time Complexity: O(N * logN), where N is the size of input array heights[].
Auxiliary Space: O(N)
7
Time Complexity: O(log(n) * mid * log(mid))