Maximum Cost of Trip With K Highways Problem
Description
LeetCode Problem 2247.
A series of highways connect n cities numbered from 0 to n - 1. You are given a 2D integer array highways where highways[i] = [city1_i, city2_i, toll_i] indicates that there is a highway that connects city1_i and city2_i, allowing a car to go from city1_i to city2_i and vice versa for a cost of toll_i.
You are also given an integer k. You are going on a trip that crosses exactly k highways. You may start at any city, but you may only visit each city at most once during your trip.
Return the maximum cost of your trip. If there is no trip that meets the requirements, return -1.
Example 1:

Input: n = 5, highways = [[0,1,4],[2,1,3],[1,4,11],[3,2,3],[3,4,2]], k = 3
Output: 17
Explanation:
One possible trip is to go from 0 -> 1 -> 4 -> 3. The cost of this trip is 4 + 11 + 2 = 17.
Another possible trip is to go from 4 -> 1 -> 2 -> 3. The cost of this trip is 11 + 3 + 3 = 17.
It can be proven that 17 is the maximum possible cost of any valid trip.
Note that the trip 4 -> 1 -> 0 -> 1 is not allowed because you visit the city 1 twice.
Example 2:

Input: n = 4, highways = [[0,1,3],[2,3,2]], k = 2
Output: -1
Explanation: There are no valid trips of length 2, so return -1.
Constraints:
2 <= n <= 151 <= highways.length <= 50highways[i].length == 30 <= city1_i, city2_i <= n - 1city1_i != city2_i0 <= toll_i <= 1001 <= k <= 50- There are no duplicate highways.
Solution
Approach: Bitmask DP
A trip crossing k highways visits k + 1 distinct cities, so when k >= n the answer is -1.
Since n <= 15, a bitmask can record which cities were visited. Let f[mask][j] be the maximum cost of a trip that visits exactly the cities in mask and ends at city j. Start with f[1 << i][i] = 0 and everything else at negative infinity.
To fill f[mask][j] (with j in mask), try every highway h -> j whose other end h is also in mask, and take f[mask without j][h] + toll. Whenever mask has exactly k + 1 bits set, the value is a candidate for the answer. The answer stays -1 if no candidate is valid.
Complexity: O(2^n * n^2) time and O(2^n * n) space.
from collections import defaultdict
from math import inf
class Solution:
def maximumCost(self, n: int, highways: List[List[int]], k: int) -> int:
if k >= n:
return -1
g = defaultdict(list)
for a, b, cost in highways:
g[a].append((b, cost))
g[b].append((a, cost))
f = [[-inf] * n for _ in range(1 << n)]
for i in range(n):
f[1 << i][i] = 0
ans = -1
for i in range(1 << n):
for j in range(n):
if i >> j & 1:
for h, cost in g[j]:
if i >> h & 1:
f[i][j] = max(f[i][j], f[i ^ (1 << j)][h] + cost)
if bin(i).count("1") == k + 1:
ans = max(ans, f[i][j])
return ans