I have given a queue initial positions increment by 1 from 1 at the front of the line to n at the back.
Any person in the queue can bribe the person directly in front of them to swap positions. If two people swap positions, they still wear the same sticker denoting their original places in line. One person can bribe at most two others. For example, if n = 8 and Person 5 bribes Person 4, the queue will look like this:1,2,3,5,4,6,7,8.
minimumbribes must print an integer representing the minimum number of bribes necessary to create the original queue, or Too chaotic if the line configuration is not possible. If no of bribes for a person exceeds to 2 then the line configuration is not possible.
minimumBribes has the following parameter(s):
- q: an array of integers.
- 1 <= n <= 100000.
Sample Input
2
5
2 1 5 3 4
5
2 5 1 3 4
Output
3
Too chaotic
Using the sorting logic I have just counted the person that comes early and are greater than following person. And it also prints the total no of bribes if the line configuration is possible else it prints Too chaotic message.
static void minimumBribes(int[] q) {
int count = 0; // Counts the no of bribes by an individual.
int j;
int total = 0; // Total no of bribes.
loop1 : for(int i = 0; i < q.length; i++) {
loop2 : for(j = i; j < q.length; j++) {
if(q[i] > q[j]) {
count++;
if(count > 2) {
System.out.println("Too chaotic");
break loop1;
}
}
else if (q[i] <= q[j]) {
total += count;
count = 0;
}
}
}
if(count <= 2)
System.out.println(total);
}
The upper mentioned code runs perfectly for a small queue but if an array has a large size, It exceeds the fixed time limit for processing.