• + 0 comments

    This is the solution for Java

        public static void minimumBribes(List<Integer> q) {
            int n = q.size();
            int bribes = 0;
    
            for(int i = n; i >= 1; i--) {
                // quick exit if number is in the right place
                if (q.get(i - 1) == i) {
                    continue;
                }
    
                // case where expected element is only one
                // places ahead
                if(q.get(i - 2) == i) {
                    bribes++;
                    Collections.swap(q, i-1, i-2);
                }
    
                // case where expected element has moved two
                // places away
                if(q.get(i - 3) == (i)) {
                    bribes += 2;
                    Collections.rotate(q.subList(i - 3, i), -1);
                }
    
                // case where expected element has moved ahead
                // further places
                else {
                    System.out.println("Too chaotic");
                    return;
                }
            }
            System.out.printf("%d\n",bribes);
        }
            }
            System.out.printf("%d\n",bribes);
        }