Minimum Cost to Reach City With Discounts - Problem

A series of highways connect n cities numbered from 0 to n - 1. You are given a 2D integer array highways where highways[i] = [city1i, city2i, tolli] indicates that there is a highway that connects city1i and city2i, allowing a car to go from city1i to city2i and vice versa for a cost of tolli.

You are also given an integer discounts which represents the number of discounts you have. You can use a discount to travel across the ith highway for a cost of tolli / 2 (integer division). Each discount may only be used once, and you can only use at most one discount per highway.

Return the minimum total cost to go from city 0 to city n - 1, or -1 if it is not possible to go from city 0 to city n - 1.

Input & Output

Example 1 — Basic Highway Network
$ Input: n = 5, highways = [[0,1,4],[1,2,3],[2,3,8],[3,4,2],[1,3,6]], discounts = 1
Output: 8
💡 Note: Optimal path: 0→1→3→4. Use discount on highway (2,3) with toll 8, making it cost 4. Total: 4 + 6 + 2 = 12. Actually, better path: 0→1→2→3→4 = 4+3+4+2 = 13 with discount on (2,3). Best is 0→1→3→4 = 4+6+2 = 12, but with discount on (1,3): 4+3+2 = 9. Wait, let me recalculate: 0→1→3→4 costs 4+6+2=12 normally, with discount on (1,3): 4+3+2=9. Actually checking: 0→1→2→3→4 = 4+3+8+2=17, with discount on (2,3): 4+3+4+2=13. So minimum is 9 via 0→1→3→4 with discount.
Example 2 — No Path Available
$ Input: n = 4, highways = [[0,1,3],[2,3,5]], discounts = 2
Output: -1
💡 Note: Cities 0-1 are connected, cities 2-3 are connected, but no path exists from city 0 to city 3. Return -1.
Example 3 — Single City
$ Input: n = 1, highways = [], discounts = 0
Output: 0
💡 Note: Already at destination (city 0 = city n-1 when n=1), so cost is 0.

Constraints

  • 1 ≤ n ≤ 1000
  • 0 ≤ highways.length ≤ 1000
  • highways[i].length == 3
  • 0 ≤ city1i, city2i ≤ n - 1
  • city1i ≠ city2i
  • 0 ≤ tolli ≤ 105
  • 0 ≤ discounts ≤ 500
  • There are no duplicate highways.

Visualization

Tap to expand
Highway Network: Find Cheapest Route with Discount Coupons01234420682StartTarget🎫 Discounts Available: 1Optimal Path: 0→1→3→4 (use discount on highway 1→3)Cost: 4 + 3 + 2 = 9 (saved 3 with discount)Minimum Total Cost: 9
Understanding the Visualization
1
Input
Highway network with tolls and available discounts
2
Process
Use modified Dijkstra considering discount states
3
Output
Minimum cost to reach destination city
Key Takeaway
🎯 Key Insight: Use modified Dijkstra treating (city, discounts_remaining) as unique states
Asked in
Google 15 Amazon 12 Microsoft 8
28.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen