[LeetCode] Maximum Cost of Trip With K Highways

2247. Maximum Cost of Trip With K Highways

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 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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
int dp[15][1<<15];
vector<pair<int, int>> adj[15];
int helper(int u, int mask, int k) {
if(k == 0) return 0;
if(dp[u][mask] != -1) return dp[u][mask];
int& res = dp[u][mask] = INT_MIN;

for(auto& [v, w] : adj[u]) {
if(mask & (1<<v)) continue;
auto ans = helper(v, mask | (1<<v), k - 1);
if(ans >= 0)
res = max(res, ans + w);
}

return res;
}
public:
int maximumCost(int n, vector<vector<int>>& H, int k) {
if(k > n) return -1;
memset(dp,-1,sizeof(dp));
for(auto& h : H) {
adj[h[0]].push_back({h[1],h[2]});
adj[h[1]].push_back({h[0],h[2]});
}
int res = INT_MIN;
for(int i = 0; i < n; i++) {
res = max(res, helper(i, 1<<i, k));
}
return res != INT_MIN ? res : -1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/04/21/PS/LeetCode/maximum-cost-of-trip-with-k-highways/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.