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.
C++ solution that safely handles casting long to int, within the time constraints.
/// safely subtract two long integers and cast to intstaticintsafeSubtAndCast(longa,longb){longresult=a-b;// Check if the result fits within the range of an intif(result<std::numeric_limits<int>::min()){// Result is less than the minimum value of int, return the minimum int valuereturnstd::numeric_limits<int>::min();}elseif(result>std::numeric_limits<int>::max()){// Result is greater than the maximum value of int, return the maximum int valuereturnstd::numeric_limits<int>::max();}else{// Result is within the range of int, perform the castreturnstatic_cast<int>(result);}}/// type alias for a pair of <int, long> elementsusingTpair=std::pair<int,long>;intminimumLoss(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(inti=0;i<price.size();++i){sorted[i]=std::make_pair(i,price[i]);}std::sort(sorted.begin(),sorted.end(),[](constTpair&a,constTpair&b){returna.second>b.second;});// compare adjacent elements, keeping track of losses and skipping gainsautoloss_best=std::numeric_limits<int>::max();for(inti=0;i<sorted.size()-1;++i){// ensure the loss came in a future yearif((sorted[i].first-sorted[i+1].first)<0){// calculate the loss for the current pairautocurr_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){return1;}elseif(curr_loss<loss_best){loss_best=curr_loss;}}}returnloss_best;}
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 →
C++ solution that safely handles casting long to int, within the time constraints.