![]() |
VOOZH | about |
Given an integer array arr[], find the sum of any two elements whose sum is closest to zero.
Note: In case if we have two ways to form sum closest to zero, return the maximum sum among them.
Examples:
Input: arr[] = [-8, 5, 2, -6]
Output: -1
Explanation: The min absolute sum pair is (5, -6)Input: arr[] = [0, -8, -6, 3]
Output: 3
Explanation: We have a tie between (0, 3) and (-6, 3). We pick the max sum in this case which is 0+3Input: arr[] = [-7, 4, 1, -2]
Output: -1
Explanation: The min absolute sum pair is (1, -2).
Table of Content
The idea is to use the naive method that checks the sum of every possible pair of elements in the array and keeps track of the pair with the minimum absolute sum.
3
The idea is to find the pair whose sum is closest to zero by sorting the array and using binary search for efficient lookup. For each element, we search for its closest complement using binary search, updating the closest sum found so far. If an exact zero sum is found, we return immediately.
Steps to implement the above idea:
3
The idea is to sort the array first and use two pointers, one at the leftmost (smallest) and the other at the rightmost (largest) element. We calculate their sum and check if it's closer to zero than our current best sum. If we find a sum of zero, we return immediately. Otherwise, we adjust the pointers based on whether the sum is positive (move right pointer left) or negative (move left pointer right).
Steps to implement the above idea:
3