Lily's Homework

  • + 1 comment

    Few cases are still failing. Not sure why

    public static int lilysHomework(List<Integer> arr) {
            
            List<Integer> sor = new ArrayList<>(arr);
            Collections.sort(sor);
            int asc = sove(sor, new ArrayList<>(arr));
            
            Collections.reverse(sor);
            int dec = sove(sor, new ArrayList<>(arr));
            return Math.min(asc, dec);
        }
        
        public static int sove(List<Integer> arr, List<Integer> org) {
            Map<Integer, Integer> iMap = new HashMap<>();
            for (int i = 0; i < org.size(); i++) {
                iMap.put(org.get(i), i);
            }
            int count = 0;
            for (int i = org.size() - 1; i >= 0; i--) {
                if(org.get(i) != arr.get(i)) {
                    int in = iMap.get(arr.get(i));
                    org.set(in, org.get(i));
                    org.set(i, arr.get(i));
                    iMap.put(org.get(i), in);
                    count++;
                }
            }
            return count;
        }