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.
importsysdefpermute(l):l=l[:1]+l[:]n=len(l)nn=n+12left=[0]*nright=[n]*nstack=left[:]arr=[0]*(nn)r=[[]for_inrange(n)]#create2dlistwithdeepcopy# after testcase 6 find left[],right[] take a round 3stop=0foriinrange(1,n):val=l[i]whiletop>0andval>l[stack[top-1]]:top-=1iftop:left[i]=stack[top-1]stack[top]=itop+=1top=0foriinrange(n-1,0,-1):val=l[i]whiletop>0andval<l[stack[top-1]]:top-=1iftop:right[i]=stack[top-1]stack[top]=itop+=1# big neck bottleans=0foriinrange(n-1,0,-1):forjinr[i]:whilej<=nn:arr[j]+=-1j+=(j&(-j))j=iwhilej<=nn:arr[j]+=1j+=(j&(-j))r[left[i]].append(i)v=0x=right[i]-1whilex>0:v+=arr[x]x-=(x&(-x))ans+=vreturnansif__name__=='__main__':n=sys.stdin.readline().split()l=tuple(map(int,sys.stdin.readline().split()))print(permute(l))
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Almost sorted interval
You are viewing a single comment's thread. Return to all comments →
Python3 solution