Skip to main content

1642. Furthest Building You Can Reach

https://leetcode.com/problems/furthest-building-you-can-reach/

Python

import heapq


class Solution:
def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
heap = []
heapq.heapify(heap)

for i in range(1, len(heights)):
diff = heights[i] - heights[i-1]

# Jump down, won't need bricks or ladders
if diff <= 0:
continue

heapq.heappush(heap, diff)
if len(heap) <= ladders:
# Ladders still enough
continue

# Use the bricks on the miniumn cost of diff
bricks -= heapq.heappop(heap)

# Running out of bricks, reach the farest building
if bricks < 0:
return i-1

# Resource is enough to reaching the end
return len(heights)-1