Sort by

recency

|

383 Discussions

|

  • + 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;
    }
    
  • + 0 comments

    Promotional items for "Minimum Loss" could focus on financial security and risk management. Custom calculators, branded notebooks for tracking investments, or practical financial planners could highlight the concept of minimizing losses. Additionally, promotional USB drives preloaded with budgeting software, or stress balls shaped like dollar signs, can serve as useful reminders. These items emphasize smart financial decisions, making them ideal for corporate giveaways or finance-related seminars.

  • + 0 comments

    C++ solution that safely handles casting long to int, within the time constraints.

    /// safely subtract two long integers and cast to int
    static int safeSubtAndCast(long a, long b)
    {
        long result = a - b;
        
        // Check if the result fits within the range of an int
        if (result < std::numeric_limits<int>::min()) {
            // Result is less than the minimum value of int, return the minimum int value
            return std::numeric_limits<int>::min();
        } else if (result > std::numeric_limits<int>::max()) {
            // Result is greater than the maximum value of int, return the maximum int value
            return std::numeric_limits<int>::max();
        } else {
            // Result is within the range of int, perform the cast
            return static_cast<int>(result);
        }
    }
    
    /// type alias for a pair of <int, long> elements
    using Tpair = std::pair<int, long>;
    
    int minimumLoss(vector<long> price)
    {
        // sort the price vector in descending order and keep track of index (i.e. year)
        std::vector<Tpair> sorted(price.size());
        for(int i = 0; i < price.size(); ++i) {
            sorted[i] = std::make_pair(i, price[i]);
        }
        std::sort(sorted.begin(), sorted.end(), [](const Tpair& a, const Tpair& b) {
            return a.second > b.second;
        });
    
        // compare adjacent elements, keeping track of losses and skipping gains
        auto loss_best = std::numeric_limits<int>::max();
        for(int i = 0; i < sorted.size() - 1; ++i) {
            // ensure the loss came in a future year
            if((sorted[i].first - sorted[i + 1].first) < 0) {
                // calculate the loss for the current pair
                auto curr_loss = safeSubtAndCast(sorted[i].second, sorted[i + 1].second);
                
                // Since the minimum loss can be no less than 1, once we find
                // a pair of housing costs that is 1, return straight away.
                // Otherwise compare the current loss to our best loss and continue
                // the comparison.
                if(curr_loss == 1) {
                    return 1;
                }
                else if(curr_loss < loss_best) {
                    loss_best = curr_loss;
                }
            }
        }
    
        return loss_best;
    }
    
  • + 0 comments
    import os
    
    def minimumLoss(price):
        # Create a list of (price, original index) tuples
        price_with_indices = [(price[i], i) for i in range(len(price))]
        
        # Sort the list by price
        price_with_indices.sort()
        
        min_loss = float('inf')
        
        # Iterate through the sorted prices and calculate the minimum loss
        for i in range(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 sell
            if current_index < previous_index:
                min_loss = min(min_loss, current_price - previous_price)
        
        return min_loss
    
    if __name__ == '__main__':
        import os  # Ensure os is imported
    
        fptr = 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()
    
  • + 0 comments
    import java.io.*;
    import java.math.*;
    import java.security.*;
    import java.text.*;
    import java.util.*;
    import java.util.concurrent.*;
    import java.util.function.*;
    import java.util.regex.*;
    import java.util.stream.*;
    import static java.util.stream.Collectors.joining;
    import static java.util.stream.Collectors.toList;
    
    class Result {
    
        /*
         * Complete the 'minimumLoss' function below.
         *
         * The function is expected to return an INTEGER.
         * The function accepts LONG_INTEGER_ARRAY price as parameter.
         */
    
        public static long minimumLoss(List<Long> price) {
    
            TreeSet<Long> priceSet = new TreeSet<>();
            long min = Long.MAX_VALUE;
            for (int i = 0; i < price.size(); i++) {
                Long higher = priceSet.higher(price.get(i));
                if (higher != null) {
                    min = Math.min(higher - price.get(i), min);     
                }
                priceSet.add(price.get(i));
            }
            
            return min;
        }
    
    }
    
    public class Solution {
        public static void main(String[] args) throws IOException {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
    
            int n = Integer.parseInt(bufferedReader.readLine().trim());
    
            List<Long> price = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
                .map(Long::parseLong)
                .collect(toList());
    
            long result = Result.minimumLoss(price);
    
            bufferedWriter.write(String.valueOf(result));
            bufferedWriter.newLine();
    
            bufferedReader.close();
            bufferedWriter.close();
        }
    }