D - Impartial Gift Editorial by evima
Another SolutionYou can calculate the answer using the following algorithm.
- Sort \(A\) in ascending order.
- For each \(B_j\), do the following:
- 2-1. Find the maximum \(A_i\) that is less than or equal to \(B_j + D\) using binary search. (If such an element does not exist, skip step 2-2.)
- 2-2. If \(A_i \geq B_j - D\), consider \(A_i + B_j\) as a candidate for the answer.
- Print the maximum among the answer candidates.
The time complexity of this solution is \(O(N \log N + M \log N)\). Note that it does not necessarily fall behind the official editorial solution, since there is no need to sort \(B\).
Sample Implementation (Python)
import bisect
N, M, D = map(int, input().split())
A = sorted(map(int, input().split()))
B = map(int, input().split())
ans = -1
for b in B:
i = bisect.bisect_right(A, b + D) - 1
if i >= 0 and A[i] >= b - D:
ans = max(ans, A[i] + b)
print(ans)
posted:
last update: