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.
defminimumBribes(q):# Can only bribe to move forward. We can take a greedy approach where we sort the # queue from the back, and only allow swaps within a specified window# if, by the end of the sort within each window, the last element is not in position,# it means they made too many bribes n=len(q)window=3num_swaps=0whilen>=window:swapped=Falseforiinrange(1,window):# compare with adjacentifq[n-i]<q[n-i-1]:q[n-i],q[n-i-1]=q[n-i-1],q[n-i]swapped=Truenum_swaps+=1ifnotswapped:# window is sortedifq[n-1]!=n:# last element is unsorted -> someone bribed more than the windowprint("Too chaotic")returnn-=1print(num_swaps)returnnum_swaps
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 →