Ctrl K

Priciest Toll Road Trip

Hard
A country has cities cities numbered from 0 to cities - 1. A triple roads[i] = [a, b, toll] is a two-way toll road between cities a and b costing toll. Any two cities are joined by at most one road. You want to drive exactly legs roads in a row, starting anywhere and never visiting a city twice. Return the largest total toll of such a trip, or -1 if no such trip exists.
Example 1
cities=4, roads=[[0, 1, 5], [1, 2, 2], [2, 3, 7], [0, 2, 4]], legs=2 → 11

The route 0 → 2 → 3 costs 4 + 7 = 11, and no two-road route costs more.

Example 2
cities=3, roads=[[0, 1, 8]], legs=2 → -1

There is a single road, and 0 → 1 → 0 is not allowed because city 0 repeats.

Example 3
cities=3, roads=[[0, 1, 8], [1, 2, 0]], legs=2 → 8

The route 0 → 1 → 2 costs 8 + 0 = 8. A free road still counts as a leg.

Constraints
  • 2 ≤ cities ≤ 15
  • 1 ≤ len(roads) ≤ 50
  • 0 ≤ a, b < cities, a ≠ b
  • 0 ≤ toll ≤ 100
  • 1 ≤ legs ≤ 50
  • Any pair of cities has at most one road
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsShortest Walk Through Every Node HardStudy Plan With a Load Cap HardSettle Up in the Fewest Transfers HardTwo Groups With the Same Average HardAssembling Fragments Hard
loading Python…
Input
cities=4, roads=[[0, 1, 5], [1, 2, 2], [2, 3, 7], [0, 2, 4]], legs=2
Expected
11

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