Most Neutral Magnet Pair
Easy · two pointers
A science club keeps a tray of small magnets. Each magnet has a whole-number charge, which can be positive, negative or zero. The list charges holds them, already sorted from smallest to largest (equal values may sit next to each other).
If you stick two different magnets together, the pair has a net charge equal to the sum of their two charges. The club wants the pair that is as close to neutral as possible.
Return the smallest possible value of |a + b| (the sum of the two charges, ignoring its sign) over all pairs of magnets at two different positions in the list. The list always has at least two magnets.
Examples
Example 1
Input: charges = [-9, -4, 1, 6, 8]
Output: 1
Pairing -9 with 8 gives -1, whose size is 1. No pair gets closer to 0 than that.
Example 2
Input: charges = [3, 5, 9]
Output: 8
Every charge is positive, so the best pair is the two smallest: 3 + 5 = 8.
Example 3
Input: charges = [-2, 0, 0, 7]
Output: 0
The two magnets with charge 0 are different magnets, and together they are neutral.
Constraints
- 2 <= len(charges) <= 3000
- -10^8 <= charges[i] <= 10^8
- charges is sorted in ascending order.