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.
In C++, just used multiset to sort the prices for fast lookup of next lower price. That speeds up enough to solve the timing issues. Use multiset not set, because the same price may exist several times:
intminimumLoss(vector<long>price){longmin=-1;multiset<long>p(price.begin(),price.end());// sort by pricefor(string::size_typei(0);i<price.size()-1;++i){autoit=p.find(price[i]);// find current price in setwhile(it!=p.begin()&&*it==price[i])--it;// find next lower price (mutimap -> while)if(*it<price[i]&&(price[i]-*it<min||min==-1))min=price[i]-*it;p.erase(price[i]);// remove current price}returnmin;}
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 →
In C++, just used
multiset
to sort the prices for fast lookup of next lower price. That speeds up enough to solve the timing issues. Usemultiset
notset
, because the same price may exist several times: