• + 0 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.

    public static int minimumLoss(List<Long> price) {
        // Write your code here
            HashMap<Long, Integer> map = new HashMap<>();
            for (int i = 0; i < price.size(); i++) {
                map.put(price.get(i),i);
            }
            Collections.sort(price);
            long min = Integer.MAX_VALUE;
            for (int i = 0; i < price.size()-1; i++) {
                long currentMin = 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;
        }