#1642
Furthest Building You Can Reach
MediumArrayGreedyHeap (Priority Queue)GreedyHeap (Priority Queue)
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n log n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n log n)Space O(n)
The optimal solution uses a min-heap (priority queue) to keep track of the jumps we make using bricks. This allows us to efficiently decide when to use a ladder for the largest jump, ensuring we maximize our reach.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a min-heap to store the heights of the jumps made with bricks.
- 2Step 2: For each building, if the next building is taller, calculate the height difference.
- 3Step 3: Use bricks for the jump and push the height difference into the min-heap.
- 4Step 4: If the number of jumps exceeds the number of ladders, remove the smallest jump from the heap and add that height to the bricks.
- 5Step 5: If at any point bricks become negative, return the last building index.
solution.py22 lines
1# Full working Python code
2import heapq
3
4def furthestBuilding(heights, bricks, ladders):
5 min_heap = []
6 n = len(heights)
7 for i in range(n - 1):
8 if heights[i] < heights[i + 1]:
9 diff = heights[i + 1] - heights[i]
10 heapq.heappush(min_heap, diff)
11 bricks -= diff
12 if len(min_heap) > ladders:
13 bricks += heapq.heappop(min_heap)
14 if bricks < 0:
15 return i
16 return n - 1
17
18# Example usage
19heights = [4, 2, 7, 6, 9, 14, 12]
20bricks = 5
21ladders = 1
22print(furthestBuilding(heights, bricks, ladders))ℹ
Complexity note: The time complexity is O(n log n) because we are using a priority queue (min-heap) to keep track of the jumps, which requires log n time for each insertion and removal.
- 1Using ladders for the largest jumps is optimal since it preserves bricks for smaller jumps.
- 2Min-heap allows efficient management of the jumps made with bricks.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.