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.
public static int lilysHomework(List<Integer> arr) {
return Math.min(minSwaps(new ArrayList<>(arr)), minSwaps(reverseList(arr)));
}
private static int minSwaps(List<Integer> arr) {
int n = arr.size();
int swaps = 0;
int[] sorted = arr.stream().mapToInt(i -> i).toArray();
Arrays.sort(sorted);
Map<Integer, Integer> indexMap = new HashMap<>();
for (int i = 0; i < n; i++) {
indexMap.put(arr.get(i), i);
}
for (int i = 0; i < n; i++) {
if (arr.get(i) != sorted[i]) {
swaps++;
int correctValue = sorted[i];
int toSwapIdx = indexMap.get(correctValue);
// Update map before swapping
indexMap.put(arr.get(i), toSwapIdx);
indexMap.put(correctValue, i);
// Swap in the list
Collections.swap(arr, i, toSwapIdx);
}
}
return swaps;
}
private static List<Integer> reverseList(List<Integer> list) {
List<Integer> reversed = new ArrayList<>(list);
Collections.reverse(reversed);
return reversed;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> arr = Arrays.stream(bufferedReader.readLine().trim().split(" "))
.map(Integer::parseInt)
.collect(Collectors.toList());
int result = Result.lilysHomework(arr);
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
Lily's Homework
You are viewing a single comment's thread. Return to all comments →
import java.io.; import java.util.; import java.util.stream.*;
class Result {
}
public class Solution { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
}