Minimum Loss 1

  • + 0 comments

    Since similar solutions rely on either a sorted array or using binary search n times where n is the length of the array, the time complexity comes out to O(nlogn) either way, I figured this is more intuitive:

    def minimumLoss(price):
        # Write your code here
        p_to_i = {}
        for i,p in enumerate(price):
            p_to_i[p] = i
        
        price.sort()
        min_value = math.inf
        for i in range(1,len(price)):
            if p_to_i[price[i-1]] > p_to_i[price[i]]:
                min_value = min(min_value,price[i] - price[i-1])
        return min_value