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.
static int size;
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner input=new Scanner(System.in);
size=input.nextInt();
//used for ascending order
Integer ar[]=new Integer[size];
// this will be used for decending array
Integer copy_ar[]=new Integer[size];
//store sorted array
Integer sort_ar[]=new Integer[size];
// store the index of array
HashMap <Integer,Integer> map=new HashMap<>();
HashMap <Integer,Integer> desMap=new HashMap<>();
int ascOrder,desOrder;
for(int index=0;index<size;index++)
{
ar[index]=input.nextInt();
map.put(ar[index],index);
}
desMap.putAll(map);
copy_ar=ar.clone();
sort_ar=ar.clone();
Arrays.sort(sort_ar);
ascOrder=countSwap(ar,map,sort_ar);
Arrays.sort(sort_ar, Collections.reverseOrder());
desOrder=countSwap(copy_ar,desMap,sort_ar);
if(ascOrder<desOrder)
{System.out.println(ascOrder);}
else
{
System.out.println(desOrder);
}
}
public static int countSwap(Integer ar[],HashMap<Integer,Integer> map,Integer sort_ar[])
{
int count=0;
int swapIndex;
for(int index=0;index<size;index++)
{
if(sort_ar[index]!=ar[index])
{
swapIndex=map.get(sort_ar[index]);
map.put(sort_ar[index],index);
map.put(ar[index],swapIndex);
ar[swapIndex]=ar[index];
ar[index]=sort_ar[index];
count++;
}
}
// System.out.println(map);
return count;
}
}
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 →
import java.io.; import java.util.;
public class Solution {
}