Tech

Apartments (CSES 1084)

Published
Published:
Table of Contents
CSES Problem Set — Chapters

Problem Link: Apartments

Approach

Sort both arrays. Use two pointers: for each applicant, find the first apartment within their tolerance range.

Solution

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n, m, k; cin >> n >> m >> k;
    vector<int> a(n), b(m);
    for (auto& x : a) cin >> x;
    for (auto& x : b) cin >> x;
    sort(a.begin(), a.end());
    sort(b.begin(), b.end());
    int i = 0, j = 0, ans = 0;
    while (i < n && j < m) {
        if (b[j] >= a[i] - k && b[j] <= a[i] + k) { ans++; i++; j++; }
        else if (b[j] < a[i] - k) j++;
        else i++;
    }
    cout << ans;
}
Support this post Sponsor