VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimum-possible-value-ai-aj-k-given-array-k/

⇱ Minimum Possible value of |ai + aj - k| for given array and k. - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimum Possible value of |ai + aj - k| for given array and k.

Last Updated : 19 Sep, 2023

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 : 
 

  1. abs( ai + aj - K) > smallest : do nothing as this pair will not count in minimal possible value.
  2. abs(ai + aj - K) = smallest : increment the count of pair resulting minimal possible value.
  3. abs( ai + aj - K) < smallest : update the smallest value and set count to 1.

Below is the implementation of the above approach: 


Output
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.
 


Output
Minimal Value = 0
Total Pairs = 4

Time Complexity : O(n Log n)
Auxiliary Space: O(n)


Comment