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.
importjava.io.*;importjava.math.*;importjava.security.*;importjava.text.*;importjava.util.*;importjava.util.concurrent.*;importjava.util.function.*;importjava.util.regex.*;importjava.util.stream.*;importstaticjava.util.stream.Collectors.joining;importstaticjava.util.stream.Collectors.toList;importjava.util.*;classResult{/* * Complete the 'minimumLoss' function below. * * The function is expected to return an INTEGER. * The function accepts LONG_INTEGER_ARRAY price as parameter. */publicstaticintminimumLoss(List<Long>price){intn=price.size();long[]priceArray=newlong[n];for(inti=0;i<n;i++){priceArray[i]=price.get(i);}// Create a map to store the original indices of pricesMap<Long,Integer>indexMap=newHashMap<>();for(inti=0;i<n;i++){indexMap.put(priceArray[i],i);}// Sort the prices in descending orderArrays.sort(priceArray);longmaxLoss=Long.MAX_VALUE;// Iterate through the sorted prices and find the maximum lossfor(inti=1;i<n;i++){if(indexMap.get(priceArray[i])<indexMap.get(priceArray[i-1])){maxLoss=Math.min(maxLoss,priceArray[i]-priceArray[i-1]);}}return(int)maxLoss;}}publicclassSolution{publicstaticvoidmain(String[]args)throwsIOException{BufferedReaderbufferedReader=newBufferedReader(newInputStreamReader(System.in));BufferedWriterbufferedWriter=newBufferedWriter(newFileWriter(System.getenv("OUTPUT_PATH")));intn=Integer.parseInt(bufferedReader.readLine().trim());List<Long>price=Stream.of(bufferedReader.readLine().replaceAll("\\s+$","").split(" ")).map(Long::parseLong).collect(toList());intresult=Result.minimumLoss(price);bufferedWriter.write(String.valueOf(result));bufferedWriter.newLine();bufferedReader.close();bufferedWriter.close();}}
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 →