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.
public static int minimumLoss(List prices) {
int n = prices.size();
Map indexMap = new HashMap<>();
for (int i = 0; i < n; i++) {
indexMap.put(prices.get(i), i);
}
List<Long> sorted = new ArrayList<>(prices);
Collections.sort(sorted, Collections.reverseOrder());
long minLoss = Long.MAX_VALUE;
for (int i = 0; i < n - 1; i++) {
long higher = sorted.get(i);
long lower = sorted.get(i + 1);
if (indexMap.get(higher) < indexMap.get(lower)) {
minLoss = Math.min(minLoss, higher - lower);
}
}
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-8 solution
public static int minimumLoss(List prices) { int n = prices.size(); Map indexMap = new HashMap<>(); for (int i = 0; i < n; i++) { indexMap.put(prices.get(i), i); }
}