Return the number whose value is closest to zero, breaking ties by choosing the larger number.
Problem
Given an integer array, find the element whose absolute value is smallest. If there is a tie, return the larger value.
You may assume the array contains at least one integer.
Clarification
- The value closest to zero is the one with the minimum absolute value.
- If two values are equally close, prefer the positive one because it is larger.
Goal
Scan the array and return the closest number to zero according to the rule above.
Input Format
- An integer array
numsof length at least 1. - Each element is an integer.
Output Format
- Return a single integer: the value closest to zero.
- If multiple values have the same absolute value, return the larger one.
Constraints
- implied typical interview scale.
- Elements may be negative, zero, or positive.
- A tie is broken by choosing the larger integer.
Example 1
Input
nums = [-4, -2, 1, 4, 8]
Output
1
Explanation
The absolute values are 4, 2, 1, 4, and 8. The smallest is 1, so the answer is 1.
Example 2
Input
nums = [2, -1, 1]
Output
1
Explanation
Both -1 and 1 are equally close to zero, but 1 is larger, so return 1.
Show 1 more example
Example 3
Input
nums = [0, 5, -3]
Output
0
Explanation
Zero is the closest possible value to zero.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.