New Year Chaos

  • + 0 comments

    Here is my solution in Java. I initially solved it by replacing the elements in list with its correct position and counting the bribes while doing that. That yielded result but few of the test cases failed due to performance. I tried a little in local IDE and took help online to arrive at this solution}

    public static void minimumBribes(List<Integer> inp) {
            int totalbribe = 0;
            int currentPerson = 0;
            int originalPosition = 0;
            int size = inp.size();
            
            //loop through all the elements
            for (int i = 0; i < size; i++){
                currentPerson = inp.get(i);
                originalPosition = currentPerson - 1;
                
                //If deviation of more than 2 position then return
                if(originalPosition - i > 2){
                    System.out.println("Too chaotic");
                    return;
                }
                
                //count the number of bribes current person has received.
                //currentPerson - 2 because if someone moved more than 2 position then it is chaotic 
                for (int j = Math.max(0, currentPerson - 2); j < i; j++){
                    if (inp.get(j) > currentPerson){
                        totalbribe++;
                    }
                }
            }
            
            System.out.println(totalbribe);
        }