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.
#include<bits/stdc++.h>usingnamespacestd;intlilysHomework(vector<int>arr,vector<int>asc,vector<int>des,intlength,map<int,int>maps){intswaps=0;map<int,int>::iteratorit;for(inti=0;i<length;i++){if(asc[i]!=arr[i]){//find the index of the element from the mapit=maps.find(asc[i]);intindex=it->second;swap(arr[i],arr[index]);//swap performed//updating the maps valueit=maps.find(arr[index]);it->second=index;swaps+=1;}}returnswaps;}intmain(){intn;cin>>n;map<int,int>maps;vector<int>arr(n);vector<int>asc(n);vector<int>des(n);for(intarr_i=0;arr_i<n;arr_i++){cin>>arr[arr_i];maps.insert(pair<int,int>(arr[arr_i],arr_i));}asc=arr;des=arr;sort(asc.begin(),asc.end());sort(des.begin(),des.end(),greater<int>());//Finding the swaps by comparing input data array withascending Sorted arrayintresult=lilysHomework(arr,asc,des,n,maps);//Finding the swaps by comparing the input data array with Descending sorted arraymaps.clear();//Reset the mapsfor(inti=0;i<n;i++)maps.insert(pair<int,int>(arr[i],i));intresult2=lilysHomework(arr,des,asc,n,maps);cout<<min(result,result2)<<endl;return0;}
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 →
My C++ Solution, Passing all test Cases :D