Minimum Loss 1

  • + 0 comments

    Java8 using TreeMap

    public static int minimumLoss(List<Long> price) {
        // Write your code here
            
            int n = price.size();
            long loss = Integer.MAX_VALUE;
            
            long lastPrice = 0;
            int lastIdx = 0;
            
            TreeMap<Long, Integer> map = new TreeMap<>();
            
            for (int i = 0; i < n; i++) {
                map.put(price.get(i), i);
            }
            
            for (Map.Entry<Long, Integer> e : map.entrySet()) {
                long curPrice = e.getKey();
                int curIdx = e.getValue();
                
                if (curIdx < lastIdx) {
                    loss = Math.min(loss, curPrice - lastPrice);
                }
                
                lastPrice = curPrice;
                lastIdx = curIdx;
            }
            
            return (int) loss;
        }