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.
Dude, should just leave Lily alone, I feel bad for helping.
packagemain;importjava.util.*;importjava.util.stream.IntStream;publicclassLilysHomework{privatestaticfinalScannerscn=newScanner(System.in);privatestaticvoidswap(long[]array,intindex1,intindex2){longtemp=array[index1];array[index1]=array[index2];array[index2]=temp;}privatestaticintswaps(long[]unsortedValues){intswaps=0;Map<Long,Integer>locations=newHashMap<>();for(inti=0;i<unsortedValues.length;i++){locations.put(unsortedValues[i],i);}long[]sortedValue=unsortedValues.clone();Arrays.sort(sortedValue);for(inti=0;i<sortedValue.length;i++){if(sortedValue[i]!=unsortedValues[i]){swaps++;intswapIndex=locations.get(sortedValue[i]);locations.put(unsortedValues[i],swapIndex);swap(unsortedValues,i,swapIndex);}}returnswaps;}publicstaticvoidmain(String[]args){intnumberOfElements=scn.nextInt();long[]values=newlong[numberOfElements];for(inti=0;i<numberOfElements;i++){intvalue=scn.nextInt();values[i]=value;}// When all you have is a hammer, everything begins to look like a nail.long[]reverseValue=IntStream.rangeClosed(1,values.length).mapToLong(i->values[values.length-i]).toArray();System.out.println(Math.min(swaps(values),swaps(reverseValue)));}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Lily's Homework
You are viewing a single comment's thread. Return to all comments →
Dude, should just leave Lily alone, I feel bad for helping.