• + 0 comments

    C#

    public static int minimumLoss(List<long> price)
    {
        var loss = long.MaxValue;
    
        var priceList = price.Select((v, i) => new { Key = v, Value = i })
            .ToDictionary(x => x.Key, x => x.Value)
            .OrderByDescending(x => x.Key)
            .ToList();
    
        for ( var i = 0; i < price.Count - 1; i++)
        {
            var priceYearNow = priceList[i];
            var priceYearNext = priceList[i + 1];
    
            if (priceYearNow.Value < priceYearNext.Value)
            {
                var diff = (priceYearNow.Key - priceYearNext.Key);
                loss = Math.Min(loss, diff);
            }
        }
    
        return (int)loss;
    }