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