• + 0 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.

    // 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.
    
    function minimumBribes(q: number[]): void {
        // Write your code here
        let total_bribes = 0
        
        for(let i=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 times
            if(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 line
           let current_bribes = 0       
            for(let j=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 optimization
                if(current_bribes === 2){  
                    break
                }
            
           }
           
           total_bribes += current_bribes // Add person's bribes to the total
        }
        process.stdout.write(total_bribes+' \n') // Return total bribes
    
    }