Ctrl K

Cheapest Hop Route

Medium
There are n towers in a row, and tower i has height heights[i]. You stand on tower 0 and want to reach the last one, n - 1, hopping forward only. From tower i you may hop to tower j > i in one of two cases: - heights[i] ≤ heights[j], and every tower strictly between them is lower than heights[i]; - heights[i] > heights[j], and every tower strictly between them is at least heights[i]. Landing on tower j costs fees[j]. Return the minimum total cost of reaching the last tower (the starting tower is free).
Example 1
heights=[4, 1, 3, 5], fees=[0, 2, 6, 3] → 3

From tower 0 (height 4) you can hop straight to tower 3 (height 5), since both towers in between are lower than 4. That costs 3. The route 0 → 1 → 2 → 3 would cost 2 + 6 + 3 = 11, and tower 2 cannot be reached from tower 0 directly.

Example 2
heights=[2, 2, 2], fees=[5, 1, 4] → 5

Tower 2 cannot be reached from tower 0 directly: the tower in between is just as tall, not lower. The only route is 0 → 1 → 2 for 1 + 4 = 5. You never pay for the starting tower.

Example 3
heights=[7], fees=[9] → 0
Constraints
  • 1 ≤ n ≤ 10⁵
  • len(heights) == len(fees) == n
  • 0 ≤ heights[i], fees[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsSum of Segment Minimums MediumTree of Leaf Products MediumAll-Ones Rectangles MediumHopping Along the Stones MediumWater Between Walls Hard
loading Python…
Input
heights=[4, 1, 3, 5], fees=[0, 2, 6, 3]
Expected
3

Run checks the first 3 tests in your browser. Submit checks all 118 tests on the server, hidden ones included.