# Apartments problem from CSES problem set

Why does my code give correct answer only for half the test cases?

#include<bits/stdc++.h>

using namespace std;

int main(){

``````int n,m;
unsigned long long k;
cin>>n>>m>>k;
vector<unsigned long long> desired(n);
for(int i=0;i<n;i++){
cin>>desired[i];
}
vector<unsigned long long> available(m);
for(int i=0;i<m;i++){
cin>>available[i];
}
int ans=0;
unordered_map<unsigned long long, int> mp;
for(int i=0;i<m;i++){
mp[available[i]]++;
}
for(int i=0;i<n;i++){
for(long long j =desired[i]-k ; j<= desired[i]+k ; j++ ){
auto it = mp.find(j);
if(it!=mp.end()){
if(it->second!=0){
ans++;
it->second=(it->second)-1;
break;
}
}
}
}
cout<<ans<<endl;

return 0;
``````

}

A simple implementation is here!

``````int solve(int n, int m, int k)
{
int i=0,j=0,ans=0;
vector<int> app(m,0),apt(n,0);

for (auto &it : apt) cin >> it;
sort(apt.begin(),apt.end());

for (auto &it : app) cin >> it;
sort(app.begin(),app.end());

while(i<n and j<m)
{
if(abs(apt[i]-app[j]) <= k)
{
ans++;
i++;
j++;
}
else if(apt[i]<app[j])
i++;
else
j++;
}
return ans;

}``````