A coastal monitoring station strings a line of buoys along a shipping channel, each anchored to a fixed point on the seabed. Every buoy reports its current horizontal drift from its own anchor, measured in meters: a negative reading means the buoy has drifted toward shore, a positive reading means it has drifted toward open sea, and a reading near zero means the buoy is sitting almost exactly on its anchor.
Given the drift readings from every buoy on the line, find the single reading that is closest to zero. If two or more readings are tied for the smallest distance from zero, report the positive one, since a seaward drift is treated as the higher-priority alert for the harbor patrol.
Line 1: an integer n — the number of buoys. Line 2: n space-separated integers d1 d2 ... dn — the drift readings, in meters.
Print a single integer: the drift reading closest to zero, breaking ties in favor of the positive value.
1 <= n <= 1000 -1000 <= di <= 1000, and di != 0 for every i
Example 1
Input
5 2 -1 1 -3 4
Expected
1
Explanation
Readings -1 and 1 are both distance 1 from the anchor, the smallest distance among all five buoys. Since it is a tie, the positive reading 1 is reported.
Example 2
Input
3 -5 -10 -3
Expected
-3
Explanation
The distances from zero are 5, 10, and 3. Buoy -3 has the smallest distance and no other buoy ties it, so -3 is reported even though it is negative.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →