I like to read this solution as a small machine: keep the useful information, throw away the noise. For 1601. Maximum Number of Achievable Transfer Requests, the solution in this repository is mainly a graph traversal solution.
Guide
What?
The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: graph traversal, backtracking.
The notes already sitting in the source point us in the right direction:
- TLE
- dfs, cycle detection
- 10 / 117 test cases passed.
Guide
When?
This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are hasCycle, maximumRequests, visited, recStack, out.
Guide
Why?
The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.
- A map keeps the lookup side cheap; the code pays a little memory to avoid repeated searching.
- The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//TLE
02//dfs, cycle detection
03//10 / 117 test cases passed.
04class Solution {
05public:
06 bool hasCycle(int cur, vector<unordered_map<int, int>>& graph,
07 vector<bool>& visited, vector<bool>& recStack, vector<int>& cycle){
08 if(!visited[cur]){
09 visited[cur] = true;
10 recStack[cur] = true;
11
12 for(const pair<int, int>& p : graph[cur]){
13 int nei = p.first;
14 if(recStack[nei]){
15 cycle.insert(cycle.begin(), nei);
16 return true;
17 }
18 if(!visited[nei] && hasCycle(nei, graph, visited, recStack, cycle)){
19 cycle.insert(cycle.begin(), nei);
20 return true;
21 }
22 }
23 }
24
25 recStack[cur] = false;
26
27 return false;
28 };
29
30 int maximumRequests(int n, vector<vector<int>>& requests) {
31 //src -> (dst, count)
32 vector<unordered_map<int, int>> graph(n);
33
34 for(const vector<int>& req : requests){
35 ++graph[req[0]][req[1]];
36 }
37
38 // for(int src = 0; src < n; ++src){
39 // cout << src << " : ";
40 // for(const pair<int,int>& p : graph[src]){
41 // cout << "(" << p.first << ", " << p.second << ") ";
42 // }
43 // cout << endl;
44 // }
45
46 int ans = 0;
47
48
49 bool stop = true;
50
51 do{
52 stop = true;
53 // cout << "hello" << endl;
54 vector<bool> visited(n, false);
55 vector<bool> recStack(n, false);
56 for(int p = 0; p < n; ++p){
57 vector<int> cycle;
58 if(!graph[p].empty() &&
59 !visited[p] && hasCycle(p, graph, visited, recStack, cycle)){
60 ans += cycle.size();
61
62 //remove cycle from graph
63 // cout << "cycle: ";
64 for(int i = 0; i < cycle.size(); ++i){
65 int start = cycle[i];
66 int end = (i+1 < cycle.size()) ? cycle[i+1] : cycle[0];
67 // cout << start << " -> ";
68 --graph[start][end];
69 if(graph[start][end] == 0){
70 graph[start].erase(end);
71 }
72 }
73 // cout << endl;
74
75 stop = false;
76 }
77 }
78 }while(!stop);
79
80
81 // for(int src = 0; src < n; ++src){
82 // cout << src << " : ";
83 // for(const pair<int,int>& p : graph[src]){
84 // cout << "(" << p.first << ", " << p.second << ") ";
85 // }
86 // cout << endl;
87 // }
88
89 return ans;
90 }
91};
92
93//enumerate all combination of requests
94//https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/discuss/866456/Python-Check-All-Combinations
95//Runtime: 1468 ms, faster than 10.64% of C++ online submissions for Maximum Number of Achievable Transfer Requests.
96//Memory Usage: 357.3 MB, less than 5.03% of C++ online submissions for Maximum Number of Achievable Transfer Requests.
97//time: O((N+R)*(2^R)), space: O(N)
98class Solution {
99public:
100 int maximumRequests(int n, vector<vector<int>>& requests) {
101 int nr = requests.size();
102 int ans = 0;
103
104 //enumerate all combination of requests
105 for(int comb = 0; comb < (1 << nr); ++comb){
106 vector<int> out(n), in(n);
107
108 for(int i = 0; i < nr; ++i){
109 // cout << comb << " " << i << endl;
110 if(comb & (1 << i)){
111 //requests[i] is chosen
112 ++out[requests[i][0]];
113 ++in[requests[i][1]];
114 }
115 }
116
117 if(in == out){
118 ans = max(ans, accumulate(out.begin(), out.end(), 0));
119 }
120 }
121
122 return ans;
123 }
124};
125
126//backtracking
127//https://leetcode.com/problems/maximum-number-of-achievable-transfer-requests/discuss/866387/Java-Backtracking-Straightforward-No-Bit-Masking
128//Runtime: 212 ms, faster than 71.74% of C++ online submissions for Maximum Number of Achievable Transfer Requests.
129//Memory Usage: 9.1 MB, less than 81.09% of C++ online submissions for Maximum Number of Achievable Transfer Requests.
130class Solution {
131public:
132 void backtrack(vector<vector<int>>& requests, int start,
133 vector<int>& in, vector<int>& out, int& ans){
134 if(start == requests.size()){
135 if(in == out){
136 ans = max(ans, accumulate(in.begin(), in.end(), 0));
137 }
138 }else{
139 // don't need the for loop here!
140 // for each request, we only have two choices: choose or not choose
141 // for(int i = start; i < requests.size(); ++i){
142 // }
143 //not choose requests[i]
144 backtrack(requests, start+1, in, out, ans);
145
146 //choose requests[i]
147 ++out[requests[start][0]];
148 ++in[requests[start][1]];
149 backtrack(requests, start+1, in, out, ans);
150 --out[requests[start][0]];
151 --in[requests[start][1]];
152 }
153 }
154
155 int maximumRequests(int n, vector<vector<int>>& requests) {
156 vector<int> in(n), out(n);
157 int ans = 0;
158
159 backtrack(requests, 0, in, out, ans);
160
161 return ans;
162 }
163};
Cost