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.
Java Solution
I sorted the price list to get the minimum cost, but i put a condition that the index of the first element of the sorted array should be greater than the index of the second one (this is to guarantee that the purchase value is greater than the sell value). To keep keep track of the index, I put the price array inside a hashmap, with the list value as the map key and the list index as the map value.
publicstaticintminimumLoss(List<Long>price){// Write your code hereHashMap<Long,Integer>map=newHashMap<>();for(inti=0;i<price.size();i++){map.put(price.get(i),i);}Collections.sort(price);longmin=Integer.MAX_VALUE;for(inti=0;i<price.size()-1;i++){longcurrentMin=price.get(i+1)-price.get(i);if(currentMin<min&&map.get(price.get(i))>map.get(price.get(i+1)))min=currentMin;}return(int)min;}
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 Solution I sorted the price list to get the minimum cost, but i put a condition that the index of the first element of the sorted array should be greater than the index of the second one (this is to guarantee that the purchase value is greater than the sell value). To keep keep track of the index, I put the price array inside a hashmap, with the list value as the map key and the list index as the map value.