Two Arrays
InterviewTime limit2sMemory limit512 MB
For each element of A, find the element of B closest in value (smallest on ties) and print the sum of these chosen values.
- Level
Medium4 of 10
- Topics
- Binary search, Sorting, Array, Two pointers
- Solved
- No attempts yet
Problem
There are integer arrays A and B. A contains n distinct positive integers, and B contains m distinct positive integers.
Using A and B, build a new array C of length n.
- C[i] is defined as the value in B closest to A[i] (the value with the smallest absolute difference).
- If several values satisfy this condition, the smallest among them is chosen.
For example, let A = [20, 5, 14, 9] and B = [16, 8, 12].
- C[1] = 16, because B[1] = 16 is closest to A[1] = 20.
- C[2] = 8, because B[2] = 8 is closest to A[2] = 5.
- C[3] = 12, because both B[1] = 16 and B[3] = 12 are closest to A[3] = 14, but B[3] is smaller.
- C[4] = 8.
For this example, C = [16, 8, 12, 8].
Given two arrays A and B, write a program that computes the new array C and finds the sum of its elements.
Input
The first line gives the number of test cases T (1 <= T <= 10).
Each test case spans three lines.
The first line gives n and m separated by a space (1 <= n, m <= 10^6).
The second line gives n space-separated integers A[1] through A[n] (each value is between 1 and 10^9).
The third line gives m space-separated integers B[1] through B[m] (each value is between 1 and 10^9).
As stated earlier, A and B are arrays of distinct positive integers.
Output
For each test case, compute the array C and print the sum of all its elements on one line.
Hint
The first test case is the one mentioned in the problem.
The second test case has A = [16, 8, 12] and B = [20, 5, 14, 9].
In this case C is [14, 9, 14], so the answer is 14+9+14 = 37.
The third test has C = [2, 2, 3], and the answer is 7.