• + 0 comments

    Java:

    public static int minimumLoss(List<Long> price) {
        // Create a sorted copy of the prices list
        List<Long> sorted = new ArrayList<>(price);
        Collections.sort(sorted);
    
        // Map to store the original index of each price
        HashMap<Long, Integer> IndexMap = new HashMap<>();
        for (int i = 0; i < price.size(); i++) {
          IndexMap.put(price.get(i), i);
        }
    
        long minLoss = Long.MAX_VALUE;
    
        // Iterate through the sorted prices to calculate the minimum loss
        for (int i = 0; i < sorted.size() - 1; i++) {
          Long next = sorted.get(i + 1);
          Long current = sorted.get(i);
          // Check if the "next" price comes after the "current" price in the
          // original list
          if (next - current < minLoss
              && IndexMap.get(next) < IndexMap.get(current)) {
            minLoss = next - current;
          }
        }
    
        return (int) minLoss;
      }
    }
    
      }
    }