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.
This might not be the most optimal, but it passes all the tests and I tried to make it easier to understand, hopefully it helps.
// Key points that helped me figure it out// - If the index (-1 because array is 0 based) and the number are the same// then the person has not bribed or been bribed// - We can count how many bribes a person has done by checking how many numbers// are after it that are greater than his/her number.functionminimumBribes(q:number[]):void{// Write your code herelettotal_bribes=0for(leti=0;i<q.length;i++){// Loop through the persons// Write your code here// If i (index) is lower than the person's number minus the 2 positions // and minus 1 because the array is 0 based (or just -3), then it means the // person bribed more than 2 timesif(i<q[i]-3){process.stdout.write("Too chaotic \n")return// Return to break out}// Check how many numbers greater than the person's current// one exist down the lineletcurrent_bribes=0for(letj=i;j<q.length;j++){// Loop through the rest of persons from current if(q[i]>q[j])current_bribes++// +1 bribe// We already know that no one bribed 3 times,// so we can break on the 2nd one for optimizationif(current_bribes===2){break}}total_bribes+=current_bribes// Add person's bribes to the total}process.stdout.write(total_bribes+'\n')// Return total bribes}
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 →
This might not be the most optimal, but it passes all the tests and I tried to make it easier to understand, hopefully it helps.