- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 47 lines of C++ from the credited upstream file 2247.cpp.
- The implementation visibly relies on sequence storage.
- 3 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int maximumCost(int n, vector<vector<int>>& highways, int k) {4 if (k + 1 > n)5 return -1;6 7 int ans = -1;8 vector<vector<int>> mem(n, vector<int>(1 << n, -1));9 vector<vector<pair<int, int>>> graph(n);10 11 for (const vector<int>& h : highways) {12 const int u = h[0];13 const int v = h[1];14 const int w = h[2];15 graph[u].emplace_back(v, w);16 graph[v].emplace_back(u, w);17 }18 19 for (int i = 0; i < n; ++i)20 ans = max(ans, maximumCost(graph, i, 1 << i, k, mem));21 22 return ans;23 }24 25 private:26 27 28 int maximumCost(const vector<vector<pair<int, int>>>& graph, int u,29 unsigned mask, int k, vector<vector<int>>& mem) {30 if (popcount(mask) == k + 1)31 return 0;32 if (mem[u][mask] != -1)33 return mem[u][mask];34 35 int res = -1;36 for (const auto& [v, w] : graph[u]) {37 if (mask >> v & 1)38 continue;39 const int nextCost = maximumCost(graph, v, mask | 1 << v, k, mem);40 if (nextCost != -1)41 res = max(res, w + nextCost);42 }43 44 return mem[u][mask] = res;45 }46};47