Last active
January 22, 2020 17:52
-
-
Save niteshghn/d338e6b928868ad2a8012a457a243d3d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#language = python3 | |
def lordOfTheRing(A): | |
stack = [] | |
for i in range(len(A)-1,-1,-1): | |
# condition for mainintain final 2 players in ring | |
if i==0 and len(stack)==1: | |
stack.append(A[0]) | |
continue | |
# inital condition | |
if not stack: | |
stack.append(A[i]) | |
else: | |
# when negative potential => pick next left player | |
if i>0 and A[i]<0: | |
if abs(A[i-1])==abs(A[i]): | |
continue | |
elif abs(A[i-1])>abs(A[i]): # winner will be left player | |
w=A[i-1] | |
else: # current player will win | |
w = A[i] | |
else: # positive potential -> check right player -> check top of stack | |
w = A[i] | |
top = stack[-1] # see who's the existing winner | |
if w>=0: # if winner is positive potential then he will fight for right (top of stack) | |
stack.pop() | |
stack.append(w if abs(w)>abs(top) else top) | |
elif abs(w)==abs(top): # disqualify both | |
stack.pop() | |
else: | |
stack.append(w) | |
# since we need either two lords of ring or none | reverse the stack to maintain order | |
return stack[::-1] if len(stack)==2 else [] | |
print(lordOfTheRing([1,1,1,1,6,1,1])) | |
print(lordOfTheRing([5,10,-5])) | |
print(lordOfTheRing([1,2,-3,5,-4,6])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment