We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
public static void minimumBribes(List q) {
// Write your code here
HashMap seen = new HashMap<>(); //To store the seen values
int min=q.size()+1;//This stores the min val found so far
int max = 0;//This stores the max val found so far
int numOfBribe = 0;// Total bribes
for(int i=q.size()-1;i>=0;i--){
//We travel from end to start and we are checking the number of
// integers less than the current number.
if(q.get(i)>max) { //If current number is greater than max then all the
//we have seen so far bribed.
if(seen.size()>2){ //If the person bribed more than 2
System.out.println("Too chaotic");
return;
}
else numOfBribe+=seen.size(); //If the person not bribed more than 2
}
else if(q.get(i)>min){ //If the current number is between min and max.
int count = 0;
for(int j=min;j<max;j++){
if(j<q.get(i)){
if(seen.containsKey(j))//we can count it as bribed if the number
count++; //is greater than min and present in seen
if(count>2){ //If the person bribed more than 2
System.out.println("Too chaotic");
return;
}
}
else{ //No more integers present in seen which are less than the
break; //current number
}
}
numOfBribe+=count; //Then we add the count to total number of bribes.
}
seen.put(q.get(i), 1); //Update map,min, and max
min = Math.min(q.get(i),min);
max = Math.max(q.get(i), max);
}
System.out.println(numOfBribe);
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
New Year Chaos
You are viewing a single comment's thread. Return to all comments →
public static void minimumBribes(List q) { // Write your code here HashMap seen = new HashMap<>(); //To store the seen values