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.
def minimumLoss(price):
indexed_prices = [(p, i) for i, p in enumerate(price)]
indexed_prices.sort(key=lambda x: x[0]) # sort by price
min_loss = float('inf')
for i in range(len(indexed_prices) - 1):
lower_price, lower_index = indexed_prices[i]
higher_price, higher_index = indexed_prices[i + 1]
# buy at lower price year, sell at higher price year (buy_index < sell_index)
# so loss is positive
if lower_index > higher_index:
loss = higher_price - lower_price
if loss < min_loss:
min_loss = loss
return min_loss
if name == "main":
n = int(input())
price = list(map(int, input().split()))
print(minimumLoss(price))
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 →
def minimumLoss(price): indexed_prices = [(p, i) for i, p in enumerate(price)] indexed_prices.sort(key=lambda x: x[0]) # sort by price
if name == "main": n = int(input()) price = list(map(int, input().split())) print(minimumLoss(price))