Lily's Homework

  • + 1 comment

    C++ solution :

    int lilysHomework(vector<int>& arr) {
        vector<int> temp = arr, sorted = arr;
        sort(sorted.begin(), sorted.end());
        unordered_map<int, int> m, mtemp;
        int count, count1=0, count2=0;
        for (int i=0;i<arr.size();i++)  m[arr[i]]=i;
        mtemp=m;
    
        for (int i=0;i<sorted.size();i++)
            if (sorted[i]!=arr[i])
            {
                count1++;
                swap(arr[i], arr[m[sorted[i]]]);
                m[arr[m[sorted[i]]]]=m[sorted[i]];
            }
        reverse(sorted.begin(), sorted.end());
        arr=temp;
        m=mtemp;
        for (int i=0;i<sorted.size();i++)
            if (sorted[i]!=arr[i])
            {
                count2++;
                swap(arr[i], arr[m[sorted[i]]]);
                m[arr[m[sorted[i]]]]=m[sorted[i]];
            }
        return count=min(count1, count2);
    }