Maps app~30 min2s · 256 MBtarget O(n log n) time, O(n) spaceclassic twin: lc-1642greedy · heaps
A maps app plans a walk across a row of rooftop terraces, from the first one to the last. Each terrace has a height in metres. A step to a lower or equal terrace costs nothing. A step up costs as much energy as the rise.
The app can also use a few lifts. One lift carries a walker up one step, whatever the rise. Your team lead says: "Show how far a walker gets with this much energy and this many lifts." A route can have 100,000 terraces.
Write furthest_terrace(heights, energy, lifts).
heights[i] is the height of terrace i. Terraces are numbered from 0, and the walker starts on terrace 0.i to terrace i + 1 costs nothing when heights[i + 1] ≤ heights[i]. Otherwise it is a climb of heights[i + 1] - heights[i].len(heights) - 1 when the whole route can be walked, and 0 when the walker cannot leave terrace 0.Input: heights = [4, 8, 2, 6, 11, 9, 15, 10], energy = 10, lifts = 2
Output: 7Pay every climb with energy first, and keep the paid climbs in a max-heap. When the energy runs out, give back the biggest paid climb and cover it with a lift.
| Step | Climb | Energy left | Paid climbs in the heap | Lifts left |
|---|---|---|---|---|
| 0 to 1 | 4 | 6 | 4 | 2 |
| 2 to 3 | 4 | 2 | 4, 4 | 2 |
| 3 to 4 | 5 | -3, then 2 after giving back 5 | 4, 4 | 1 |
| 5 to 6 | 6 | -4, then 2 after giving back 6 | 4, 4 | 0 |
The steps 1 to 2, 4 to 5 and 6 to 7 go down, so they are free. The walker reaches terrace 7.
Input: heights = [3, 9, 4, 10, 5], energy = 4, lifts = 1
Output: 2There are two climbs of 6. One is covered by the lift. The other needs 6 energy, and there are only 4. The walker stops on terrace 2.
Input: heights = [6, 2, 2, 2], energy = 0, lifts = 0
Output: 3Every step goes down or across, so no energy is needed.
1 ≤ length of heights ≤ 10^5, and 1 ≤ heights[i] ≤ 10^60 ≤ energy ≤ 10^90 ≤ lifts ≤ 10^5Choosing which climbs get a lift is a choice of a subset. With 50,000 climbs and 20,000 lifts, the number of subsets is beyond any limit, so you need a rule that builds the choice as you walk.
A heap of the climbs paid so far gives the largest one in one step. A walk of 100,000 steps with a pop and a push each is about 100,000 × 17 steps. The energy used never passes energy plus one climb, which is below 2 × 10^9.