• + 0 comments

    Java solution with TreeSet that provides a higher function to query the closest higher element.

        public static int minimumLoss(List<Long> prices) {
            var sortedPrices = new TreeSet<Long>();
            var minimumLoss = (long) Integer.MAX_VALUE;
            for (var price : prices) {
                var higher = sortedPrices.higher(price);
                if (higher != null) {
                    minimumLoss = Math.min(minimumLoss, higher - price);
                }
                sortedPrices.add(price);
            }
            return (int) minimumLoss;
        }