A speed contest of decent quality. Some problems are worth thinking about: only after discovering the essence can you solve them quickly.
1460. Make Two Arrays Equal by Reversing Sub-arrays
Because there is no limit on the number of reverse operations, we can construct a strategy to transform two arrays into the same array. Similar to selection sort, each reverse can put one position in order. So the problem becomes: after sorting the two arrays, are they equal? In C++, vector‘s == does exactly this.
Time complexity: O(N log N), Space complexity: O(1).
classSolution { public: vector<bool> checkIfPrerequisite(int n, vector<vector<int>>& prerequisites, vector<vector<int>>& queries){ unordered_map<int, vector<int>> edges; for (constauto& v : prerequisites) { edges[v[1]].push_back(v[0]); } map<pair<int,int>, bool> memo; function<bool(int,int,unordered_set<int>&)> dfs = [&](int root, int target, unordered_set<int>& seen) -> bool { if (memo.find({root, target}) == memo.end()) { if (target == root) return memo[{root, target}] = true; for (int neighbor : edges[root]) { if (seen.find(neighbor) == seen.end()) { seen.insert(neighbor); if (dfs(neighbor, target, seen)) return memo[{root, target}] = true; } } return memo[{root, target}] = false; } else { return memo[{root, target}]; } }; vector<bool> ans(queries.size()); for (int i = 0; i < queries.size(); ++i) { unordered_set<int> seen; ans[i] = dfs(queries[i][1], queries[i][0], seen); } return ans; } };
The Discuss section mentions that the Floyd-Warshall algorithm can be used to compute the shortest distance between two nodes in a directed graph.
1463. Cherry Pickup II
DP. dp[i][first][second]: when the robots reach row i, with the first robot at first and the second at second, the maximum number of cherries picked.
dp[i][first][second] = max(dp[i-1][for last_first in range(first - 1, first + 2)])[for last_second in range(second - 1, second + 2)] + (grid[i][first] + grid[i][second]) if first != second else grid[i][first].
Time complexity: O(rows * cols^2 * 9), Space complexity: O(rows * cols^2) -> O(cols^2).