Skyscraper Furthest Distance
A player needs to traverse between skyscrapers, carrying springs and sandbags. The heights of these buildings vary.
If the next building's rooftop is lower than or equal to the current one, the player can move freely.
If the next rooftop is higher, the player must either:
- Use sandbags (each sandbag increases the player's height by 1; if the sum of the current height and sandbags equals the next rooftop's height, the player can move forward).
- Use springs to jump directly to the next rooftop, regardless of height difference.
The goal is to determine the index of how far the player can travel.
Example 1:
Example 2:
Example 3:
Notes
Intuition
Springs are most valuable for the largest height differences. Use sandbags first, and when you run out, retroactively convert the largest sandbag usage to a spring.
Implementation
Use a max heap to track height differences. For each upward jump, subtract from sandbags and add the difference to the heap. If sandbags go negative and no springs remain, return the current index. Otherwise, use a spring by popping the largest jump from the heap and adding those sandbags back. Continue until the end.
Edge-cases
Python's heapq is a min heap—negate values to simulate max heap behavior. Remember to negate again when popping.
- Time: O(n log n) — heap operations for each building
- Space: O(n) — heap stores jump sizes