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 Python 3 code with a customized binary search tree. Passed all the tess. I know in the worst case, this is O(n^2). But in most cases, it is like O(n log n), if the tree is somewhat balanced.
min_loss = float('inf')
root = Node(price[0])
prev = root
for p in price:
current = root
while True:
if current is None:
if p > prev.val:
prev.right = Node(p)
break
elif p < prev.val:
prev.left = Node(p)
break
elif current.val == p:
break
elif current.val < p:
prev = current
current = current.right
elif current.val > p:
prev = current
min_loss = min(min_loss, current.val - p)
current = current.left
return min_loss
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Minimum Loss
You are viewing a single comment's thread. Return to all comments →
My Python 3 code with a customized binary search tree. Passed all the tess. I know in the worst case, this is O(n^2). But in most cases, it is like O(n log n), if the tree is somewhat balanced.
class Node: def init(self, key): self.left = None self.right = None self.val = key
def minimumLoss(price): # Write your code here