![]() |
VOOZH | about |
You are given an array of n integer and an integer K. Find the number of total unordered pairs {i, j} such that absolute value of (ai + aj - K), i.e., |ai + aj - k| is minimal possible, where i != j.
Examples:
Input: arr[] = {0, 4, 6, 2, 4}, K = 7
Output: Minimal Value = 1, Total Pairs = 5
Explanation: Pairs resulting minimal value are : {a1, a3}, {a2, a4}, {a2, a5}, {a3, a4}, {a4, a5}
Input: arr[] = {4, 6, 2, 4} , K = 9
Output: Minimal Value = 1, Total Pairs = 4
Explanation: Pairs resulting minimal value are : {a1, a2}, {a1, a4}, {a2, a3}, {a2, a4}
A simple solution is iterate over all possible pairs and for each pair we will check whether the value of (ai + aj - K) is smaller than our current smallest value of not. So as per result of above condition we have total of three cases :
Below is the implementation of the above approach:
Minimal Value = 0 Total Pairs = 4
Time Complexity: O(n2) where n is the number of elements in the array.
Auxiliary Space : O(1)
An efficient solution is to use a self balancing binary search tree (which is implemented in set in C++ and TreeSet in Java). We can find closest element in O(log n) time in map.
Minimal Value = 0 Total Pairs = 4
Time Complexity : O(n Log n)
Auxiliary Space: O(n)