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.
importosdefminimumLoss(price):# Create a list of (price, original index) tuplesprice_with_indices=[(price[i],i)foriinrange(len(price))]# Sort the list by priceprice_with_indices.sort()min_loss=float('inf')# Iterate through the sorted prices and calculate the minimum lossforiinrange(1,len(price_with_indices)):current_price,current_index=price_with_indices[i]previous_price,previous_index=price_with_indices[i-1]# Ensure that we buy before we sellifcurrent_index<previous_index:min_loss=min(min_loss,current_price-previous_price)returnmin_lossif__name__=='__main__':importos#Ensureosisimportedfptr=open(os.environ['OUTPUT_PATH'],'w')n=int(input().strip())price=list(map(int,input().rstrip().split()))result=minimumLoss(price)fptr.write(str(result)+'\n')fptr.close()
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 →