We can use a greedy approach to solve this problem. First, sort the applicants and apartments. We can keep two pointers and (initialized to 0), which keep track of the current index of the applicant and apartment we are looking at respectively. Then, while there are more applicants and apartments to look through, we repeatedly run the following check:
- If , we have found a suitable apartment for the current applicant. Thus, we increment , , and our answer.
- Otherwise, is either too big or too small for . We can increment or accordingly.
Implementation
Time Complexity:
n, m, tolerance = map(int, input().split())applicants = list(map(int, input().split()))apartments = list(map(int, input().split()))applicants.sort()apartments.sort()i = 0 # Applicant pointerj = 0 # Apartment pointerans = 0while i < n and j < m:
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!