Advertisement
Guest User

Untitled

a guest
Dec 15th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. package codility;
  2.  
  3.  
  4. public class Solution {
  5.     public int solution(int[] A){
  6.         boolean[] visited = new boolean[A.length];
  7.         int max = 0;
  8.         int head;
  9.         int tail;
  10.         int counter;
  11.  
  12.         if(A.length > 0){
  13.             for(int i=0; i<A.length; i++){
  14.                 counter = 1;
  15.                 head = i;
  16.                 tail = A[i];
  17.  
  18.                 if(head != tail){
  19.                     if(!visited[head] || head == 0){
  20.                         visited[head] = true;
  21.                         visited[tail] = true;
  22.  
  23.                         while(head != tail){
  24.                             tail = A[tail];
  25.                             visited[tail] = true;
  26.                             counter++;
  27.                         }
  28.                     }
  29.                 }
  30.                 if(counter > max)
  31.                     max = counter;
  32.             }
  33.  
  34.         }
  35.         return max;
  36.  
  37.     }
  38.  
  39.     public static void main(String[] args) {
  40.  
  41.         Solution solution = new Solution();
  42.         int test[] = new int[] {5,4,0,3,1,6,2};
  43.         System.out.println(solution.solution(test));
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement