#K71302. Closest Candy Sweetness
Closest Candy Sweetness
Closest Candy Sweetness
Given a sorted or unsorted list of candy sweetness levels and a list of customer desired sweetness values, for each customer, determine the candy with the closest sweetness level to the desired value. In case of a tie, the candy with the lower sweetness level is chosen.
Mathematically, for a customer with desired sweetness value x and a candy with sweetness level c, you need to minimize the absolute difference:
If there are two candidates c1 and c2 such that \(|c1-x| = |c2-x|\), then choose \(\min(c1, c2)\).
The input is given via standard input and the output should be printed to standard output.
inputFormat
The first line contains two integers n
and m
where n
is the number of candies and m
is the number of customers.
The second line contains n
space-separated integers representing the sweetness levels of the candies.
The third line contains m
space-separated integers representing the customers' desired sweetness values.
outputFormat
Print a single line with m
integers separated by a single space. Each integer represents the sweetness level of the candy that is closest to the corresponding customer's desired value.
5 3
1 3 5 7 9
2 4 8
1 3 7