Suppose, there are n number of houses of different heights and a parkour artist wants to go from one house to another with help of some bricks and ladders. The heights of the houses are given to us as an array. Each brick is a unit length tall and we are given a handful of those. We can use the ladders and the bricks only once. We have to find out the furthest building the parkour artist can go to.
So, if the input is like heights = [5, 8, 7, 6, 2, 3, 1, 4], bricks = 3, ladders = 2, then the output will be 7.
The artist starts from building 0.
He reaches building 1 with the help of the 3 bricks.
He jumps to building 2, 3, 4 as the successor buildings are shorter than the predecessor ones.
He uses a ladder to go from building 4 to building 5.
He jumps from building 5 to building 6 as building 6 is shorter.
He uses the last ladder to reach building 7.
To solve this, we will follow these steps −
temp := a new heap
for i in range 1 to size of heights, do
dist := heights[i] - heights[i - 1]
if dist > 0, then
bricks := bricks - dist
push value -dist to the heap temp
if bricks < 0, then
ladders := ladders - 1
bricks := bricks - the smallest element removed from heap temp
if bricks < 0 or ladders < 0, then
return i - 1
return size of heights - 1
Example
Let us see the following implementation to get better understanding −
from heapq import heappush, heappop def solve(heights, bricks, ladders): temp = [] for i in range(1, len(heights)): dist = heights[i] - heights[i - 1] if dist > 0: bricks -= dist heappush(temp, -dist) if bricks < 0: ladders -= 1 bricks -= heappop(temp) if bricks < 0 or ladders < 0: return i - 1 return len(heights) - 1 print(solve([5, 8, 7, 6, 2, 3, 1, 4], 3, 2))
Input
[5, 8, 7, 6, 2, 3, 1, 4], 3, 2
Output
7