Advertisement
rajeshinternshala

Untitled

Oct 3rd, 2023
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.96 KB | None | 0 0
  1.     int ans = 0;
  2.     public int maximumInvitations(int[] favorite) {
  3.         List<List<Integer>> graph = new ArrayList<>();
  4.         int n = favorite.length;
  5.         for (int i = 0; i <= n; i++) {
  6.             graph.add(new ArrayList<>());
  7.         }
  8.         for (int i = 0; i < n; i++) {
  9.             int index = i + 1;
  10.             graph.get(index).add(favorite[i]);
  11.             graph.get(favorite[i]).add(index);
  12.         }
  13.         ans = 0;
  14.         HashSet<Integer> visited = new HashSet<>();
  15.         for (int i = 1; i <= n; i++) {
  16.             if (!visited.contains(i))
  17.                 dfs(i, graph, visited, 1);
  18.         }
  19.         return ans;
  20.     }
  21.  
  22.     private void dfs(int i, List<List<Integer>> graph, HashSet<Integer> visited, int count) {
  23.         visited.add(i);
  24.         ans = Math.max(ans, count);
  25.         for (int u : graph.get(i)) {
  26.             if (!visited.contains(u)) {
  27.                 dfs(u, graph, visited, count + 1);
  28.             }
  29.         }
  30.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement