Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int ans = 0;
- public int maximumInvitations(int[] favorite) {
- List<List<Integer>> graph = new ArrayList<>();
- int n = favorite.length;
- for (int i = 0; i <= n; i++) {
- graph.add(new ArrayList<>());
- }
- for (int i = 0; i < n; i++) {
- int index = i + 1;
- graph.get(index).add(favorite[i]);
- graph.get(favorite[i]).add(index);
- }
- ans = 0;
- HashSet<Integer> visited = new HashSet<>();
- for (int i = 1; i <= n; i++) {
- if (!visited.contains(i))
- dfs(i, graph, visited, 1);
- }
- return ans;
- }
- private void dfs(int i, List<List<Integer>> graph, HashSet<Integer> visited, int count) {
- visited.add(i);
- ans = Math.max(ans, count);
- for (int u : graph.get(i)) {
- if (!visited.contains(u)) {
- dfs(u, graph, visited, count + 1);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement