Lily's Homework

  • + 0 comments

    My solution only passed test case 0, 7, 10 and 11. Does anyone know why?

    public static int lilysHomework(List<Integer> arr) {
            List<Integer> ascendingSorted = new ArrayList<>(arr);
            List<Integer> descendingSorted = new ArrayList<>(arr);
            Collections.sort(ascendingSorted);
            Collections.sort(descendingSorted, (a,b) -> (b - a));
            
            if(arr.equals(ascendingSorted) || arr.equals(descendingSorted))
                return 0;
                
            List<Integer> ascendingList = new ArrayList<>(arr);
            List<Integer> descendingList = new ArrayList<>(arr);
            
            Map<Integer, Integer> ascendingIdxMap = new HashMap<>();
            Map<Integer, Integer> descendingIdxMap = new HashMap<>();
            for(int i = 0; i < arr.size(); i++){
                ascendingIdxMap.put(ascendingSorted.get(i), i);
                descendingIdxMap.put(descendingSorted.get(i), i);
            }
            int ascCount = 0, desCount = 0;
            for(int i = 0; i < arr.size(); i++){
                if(ascendingList.get(i) != ascendingSorted.get(i)){
                    int tmp = ascendingList.get(i);
                    int idx = ascendingIdxMap.get(ascendingList.get(i));
                    ascendingList.set(idx, tmp);
                    ascCount++;
                }                
                if(descendingList.get(i) != descendingSorted.get(i)){
                    int tmp = descendingList.get(i);
                    int idx = descendingIdxMap.get(descendingList.get(i));
                    descendingList.set(idx, tmp);
                    desCount++;
                }                
            }
            return Math.min(ascCount, desCount);
        }