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.
My answer with Typescript, idea & explain includes.
functionminimumBribes(q:number[]):void{/** * Idea: Reverse thinking, complete the numbers behind first, count the number * of permutations of the argument. */// 0. fn that swap number in arrayconstswap=(s:number[],i:number)=>{[s[i],s[i+1]]=[s[i+1],s[i]]}// 1. create fresh new array to be start, a hash to couting swapedlets=Array(q.length).fill(0).map((_,i)=>i+1)letswap_count=newMap<number,number>()// 2. loop [q], find and swap to complete right side to left side, counting too.mainloop:for(letqi=q.length-1;qi>=0;qi--){while(true){letsi=s.indexOf(q[qi])if(si<qi){letswap_num=s[si+1]swap(s,si)swap_count.set(swap_num,(swap_count.get(swap_num)||0)+1)continue}break;}}// 3. calc swaping is chaos or notletcounts=Array.from(swap_count.values())letchaos=counts.some(e=>e>2)letsum=counts.reduce((p,v)=>p+v,0)if(chaos)console.log('Toochaotic')elseconsole.log(sum)}
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 →
My answer with Typescript, idea & explain includes.