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.
publicstaticintminimumLoss(List<Long>price){// Create a sorted copy of the prices listList<Long>sorted=newArrayList<>(price);Collections.sort(sorted);// Map to store the original index of each priceHashMap<Long,Integer>IndexMap=newHashMap<>();for(inti=0;i<price.size();i++){IndexMap.put(price.get(i),i);}longminLoss=Long.MAX_VALUE;// Iterate through the sorted prices to calculate the minimum lossfor(inti=0;i<sorted.size()-1;i++){Longnext=sorted.get(i+1);Longcurrent=sorted.get(i);// Check if the "next" price comes after the "current" price in the// original listif(next-current<minLoss&&IndexMap.get(next)<IndexMap.get(current)){minLoss=next-current;}}return(int)minLoss;}}}}
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 →
Java: