Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice on BST
  • MCQs on BST
  • BST Tutorial
  • BST Insertion
  • BST Traversals
  • BST Searching
  • BST Deletion
  • Check BST
  • Balance a BST
  • Self-Balancing BST
  • AVL Tree
  • Red-Black Tree
  • Splay Tree
  • BST Application
  • BST Advantage
Open In App
Next Article:
Special two digit numbers in a Binary Search Tree
Next article icon

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

Last Updated : 19 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 

C++




// CPP program to find number of pairs  and minimal
// possible value
#include <bits/stdc++.h>
using namespace std;
  
// function for finding pairs and min value
void pairs(int arr[], int n, int k)
{
    // initialize smallest and count
    int smallest = INT_MAX;
    int count = 0;
  
    // iterate over all pairs
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++) {
            // is abs value is smaller than smallest
            // update smallest and reset count to 1
            if (abs(arr[i] + arr[j] - k) < smallest) {
                smallest = abs(arr[i] + arr[j] - k);
                count = 1;
            }
  
            // if abs value is equal to smallest
            // increment count value
            else if (abs(arr[i] + arr[j] - k) == smallest)
                count++;
        }
  
    // print result
    cout << "Minimal Value = " << smallest << "\n";
    cout << "Total Pairs = " << count << "\n";
}
  
// driver program
int main()
{
    int arr[] = { 3, 5, 7, 5, 1, 9, 9 };
    int k = 12;
    int n = sizeof(arr) / sizeof(arr[0]);
    pairs(arr, n, k);
    return 0;
}
 
 

Java




// Java program to find number of pairs
// and minimal possible value
import java.util.*;
  
class GFG {
  
    // function for finding pairs and min value
    static void pairs(int arr[], int n, int k)
    {
        // initialize smallest and count
        int smallest = Integer.MAX_VALUE;
        int count = 0;
  
        // iterate over all pairs
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++) {
                // is abs value is smaller than
                // smallest update smallest and
                // reset count to 1
                if (Math.abs(arr[i] + arr[j] - k)
                    < smallest) {
                    smallest
                        = Math.abs(arr[i] + arr[j] - k);
                    count = 1;
                }
  
                // if abs value is equal to smallest
                // increment count value
                else if (Math.abs(arr[i] + arr[j] - k)
                         == smallest)
                    count++;
            }
  
        // print result
        System.out.println("Minimal Value = " + smallest);
        System.out.println("Total Pairs = " + count);
    }
  
    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int arr[] = { 3, 5, 7, 5, 1, 9, 9 };
        int k = 12;
        int n = arr.length;
        pairs(arr, n, k);
    }
}
// This code is contributed by Arnav Kr. Mandal.
 
 

Python3




# Python3 program to find number of pairs
# and minimal possible value
  
# function for finding pairs and min value
  
  
def pairs(arr, n, k):
  
    # initialize smallest and count
    smallest = 999999999999
    count = 0
  
    # iterate over all pairs
    for i in range(n):
        for j in range(i + 1, n):
  
            # is abs value is smaller than smallest
            # update smallest and reset count to 1
            if abs(arr[i] + arr[j] - k) < smallest:
                smallest = abs(arr[i] + arr[j] - k)
                count = 1
  
            # if abs value is equal to smallest
            # increment count value
            elif abs(arr[i] + arr[j] - k) == smallest:
                count += 1
  
    # print result
    print("Minimal Value = ", smallest)
    print("Total Pairs = ", count)
  
  
# Driver Code
if __name__ == '__main__':
    arr = [3, 5, 7, 5, 1, 9, 9]
    k = 12
    n = len(arr)
    pairs(arr, n, k)
  
# This code is contributed by PranchalK
 
 

C#




// C# program to find number
// of pairs and minimal
// possible value
using System;
  
class GFG {
  
    // function for finding
    // pairs and min value
    static void pairs(int[] arr, int n, int k)
    {
        // initialize
        // smallest and count
        int smallest = 0;
        int count = 0;
  
        // iterate over all pairs
        for (int i = 0; i < n; i++)
            for (int j = i + 1; j < n; j++) {
                // is abs value is smaller
                // than smallest update
                // smallest and reset
                // count to 1
                if (Math.Abs(arr[i] + arr[j] - k)
                    < smallest) {
                    smallest
                        = Math.Abs(arr[i] + arr[j] - k);
                    count = 1;
                }
  
                // if abs value is equal
                // to smallest increment
                // count value
                else if (Math.Abs(arr[i] + arr[j] - k)
                         == smallest)
                    count++;
            }
  
        // print result
        Console.WriteLine("Minimal Value = " + smallest);
        Console.WriteLine("Total Pairs = " + count);
    }
  
    // Driver Code
    public static void Main()
    {
        int[] arr = { 3, 5, 7, 5, 1, 9, 9 };
        int k = 12;
        int n = arr.Length;
        pairs(arr, n, k);
    }
}
  
// This code is contributed
// by anuj_67.
 
 

PHP




<?php
// PHP program to find number of
// pairs and minimal possible value
  
// function for finding pairs
// and min value
function pairs($arr, $n, $k)
{
      
    // initialize smallest and count
    $smallest = PHP_INT_MAX;
    $count = 0;
  
    // iterate over all pairs
    for ($i = 0; $i < $n; $i++)
        for($j = $i + 1; $j < $n; $j++)
        {
              
            // is abs value is smaller than smallest
            // update smallest and reset count to 1
            if ( abs($arr[$i] + $arr[$j] - $k) < $smallest )
            { 
                $smallest = abs($arr[$i] + $arr[$j] - $k);
                $count = 1;
            }
  
            // if abs value is equal to smallest
            // increment count value
            else if (abs($arr[$i] + 
                     $arr[$j] - $k) == $smallest)
                $count++;
        }
  
        // print result
        echo "Minimal Value = " , $smallest , "\n";
        echo "Total Pairs = ", $count , "\n"; 
} 
  
    // Driver Code
    $arr = array (3, 5, 7, 5, 1, 9, 9);
    $k = 12;
    $n = sizeof($arr);
    pairs($arr, $n, $k);
  
// This code is contributed by aj_36 
?>
 
 

Javascript




<script>
  
// Javascript program to find number of pairs  and minimal 
// possible value
  
// function for finding pairs and min value
function pairs(arr, n, k)
{
    // initialize smallest and count
    var smallest = 1000000000;
    var count=0;
  
    // iterate over all pairs
    for (var i=0; i<n; i++)
        for(var j=i+1; j<n; j++)
        {
            // is Math.abs value is smaller than smallest
            // update smallest and reset count to 1
            if ( Math.abs(arr[i] + arr[j] - k) < smallest )
            { 
                smallest = Math.abs(arr[i] + arr[j] - k);
                count = 1;
            }
  
            // if Math.abs value is equal to smallest
            // increment count value
            else if (Math.abs(arr[i] + arr[j] - k) == smallest)
                count++;
        }
  
        // print result
        document.write( "Minimal Value = " + smallest + "<br>");
        document.write( "Total Pairs = " + count + "<br>");    
} 
  
// driver program
var arr = [3, 5, 7, 5, 1, 9, 9];
var k = 12;
var n = arr.length;
pairs(arr, n, k);
  
</script>
 
 
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.
 

C++




// C++ program to find number of pairs
// and minimal possible value
#include <bits/stdc++.h>
using namespace std;
  
// function for finding pairs and min value
void pairs(int arr[], int n, int k)
{
    // initialize smallest and count
    int smallest = INT_MAX, count = 0;
    set<int> s;
  
    // iterate over all pairs
    s.insert(arr[0]);
    for (int i = 1; i < n; i++) {
        // Find the closest elements to  k - arr[i]
        int lower
            = *lower_bound(s.begin(), s.end(), k - arr[i]);
  
        int upper
            = *upper_bound(s.begin(), s.end(), k - arr[i]);
  
        // Find absolute value of the pairs formed
        // with closest greater and smaller elements.
        int curr_min = min(abs(lower + arr[i] - k),
                           abs(upper + arr[i] - k));
  
        // is abs value is smaller than smallest
        // update smallest and reset count to 1
        if (curr_min < smallest) {
            smallest = curr_min;
            count = 1;
        }
  
        // if abs value is equal to smallest
        // increment count value
        else if (curr_min == smallest)
            count++;
        s.insert(arr[i]);
  
    } // print result
  
    cout << "Minimal Value = " << smallest << "\n";
    cout << "Total Pairs = " << count << "\n";
}
  
// driver program
int main()
{
    int arr[] = { 3, 5, 7, 5, 1, 9, 9 };
    int k = 12;
    int n = sizeof(arr) / sizeof(arr[0]);
    pairs(arr, n, k);
    return 0;
}
 
 

Python3




# Python program to find number of pairs
# and minimal possible value
  
from sys import maxsize
from bisect import bisect_left, bisect_right
  
# function for finding pairs and min value
def pairs(arr, n, k):
    # initialize smallest and count
    smallest = maxsize
    count = 0
    s = set()
  
    # iterate over all pairs
    s.add(arr[0])
    for i in range(1, n):
        # Find the closest elements to k - arr[i]
        sorted_s = sorted(s)
        index = bisect_left(sorted_s, k - arr[i])
        if index == len(sorted_s):
            lower = sorted_s[index - 1]
        else:
            lower = sorted_s[index]
        index = bisect_right(sorted_s, k - arr[i])
        if index == len(sorted_s):
            upper = sorted_s[index - 1]
        else:
            upper = sorted_s[index]
  
        # Find absolute value of the pairs formed
        # with closest greater and smaller elements.
        curr_min = min(abs(lower + arr[i] - k), abs(upper + arr[i] - k))
  
        # is abs value is smaller than smallest
        # update smallest and reset count to 1
        if curr_min < smallest:
            smallest = curr_min
            count = 1
        # if abs value is equal to smallest
        # increment count value
        elif curr_min == smallest:
            count += 1
        s.add(arr[i])
  
    # print result
    print("Minimal Value = ", smallest)
    print("Total Pairs = ", count)
  
# driver program
arr = [3, 5, 7, 5, 1, 9, 9]
k = 12
n = len(arr)
pairs(arr, n, k)
  
# This code is contributed by vikramshirsath177.
 
 

Java




import java.util.*;
  
class Main {
    // function for finding pairs and min value
    static void pairs(final int[] arr,final int n,final int k) {
        // initialize smallest and count
        int smallest = Integer.MAX_VALUE, count = 0;
        Set<Integer> s = new TreeSet<>();
  
        // iterate over all pairs
        s.add(arr[0]);
        for (int i = 1; i < n; i++) {
            // Find the closest elements to  k - arr[i]
            int lower = Integer.MIN_VALUE;
            int upper = Integer.MAX_VALUE;
            for (Integer x : s) {
                if (x <= (k - arr[i]) && x >= lower) {
                   lower = x;
                 }
                if (x >= (k - arr[i]) && x <= upper) {
                    upper = x;
                 }
             }
  
            // Find absolute value of the pairs formed
            // with closest greater and smaller elements.
            int curr_min = Math.min(Math.abs(lower + arr[i] - k), Math.abs(upper + arr[i] - k));
  
            // is abs value is smaller than smallest
            // update smallest and reset count to 1
            if (curr_min < smallest) {
                smallest = curr_min;
                count = 1;
            }
  
            // if abs value is equal to smallest
            // increment count value
            else if (curr_min == smallest)
                count++;
            s.add(arr[i]);
  
        } // print result
  
        System.out.println("Minimal Value = " + smallest);
        System.out.println("Total Pairs = " + count);
    }
  
    // driver program
    public static void main(String[] args) {
        int[] arr = {3, 5, 7, 5, 1, 9, 9};
        int k = 12;
        int n = arr.length;
        pairs(arr, n, k);
    }
}
 
 

Javascript




function pairs(arr, n, k) {
    // initialize smallest and count
    let smallest = Number.MAX_SAFE_INTEGER;
    let count = 0;
    let s = new Set();
   
    // iterate over all pairs
    s.add(arr[0]);
    for (let i = 1; i < n; i++) {
        // Find the closest elements to  k - arr[i]
        let lower = [...s].find((element) => element >= k - arr[i]);
        let upper = [...s].find((element) => element >= k - arr[i]);
   
        // Find absolute value of the pairs formed
        // with closest greater and smaller elements.
        let curr_min = Math.min(Math.abs(lower + arr[i] - k), Math.abs(upper + arr[i] - k));
   
        // if abs value is smaller than smallest
        // update smallest and reset count to 1
        if (curr_min < smallest) {
            smallest = curr_min;
            count = 1;
        }
        // if abs value is equal to smallest
        // increment count value
        else if (curr_min === smallest)
            count++;
        s.add(arr[i]);
    }
   
    // print result
    console.log(`Minimal Value = ${smallest}`);
    console.log(`Total Pairs = ${count}`);
}
   
// driver program
let arr = [3, 5, 7, 5, 1, 9, 9];
let k = 12;
let n = arr.length;
pairs(arr, n, k);
 
 

C#




using System;
using System.Collections.Generic;
using System.Linq;
  
class Program
{
    // function for finding pairs and min value
    static void pairs(int[] arr, int n, int k)
    {
        // initialize smallest and count
        int smallest = int.MaxValue, count = 0;
        SortedSet<int> s = new SortedSet<int>();
  
        // iterate over all pairs
        s.Add(arr[0]);
        for (int i = 1; i < n; i++)
        {
            // Find the closest elements to k - arr[i]
            int lower = s.Where(e => e >= k - arr[i]).DefaultIfEmpty(int.MinValue).First();
            int upper = s.Where(e => e > k - arr[i]).DefaultIfEmpty(int.MaxValue).First();
  
            // Find absolute value of the pairs formed
            // with closest greater and smaller elements.
            int curr_min = Math.Min(Math.Abs(lower + arr[i] - k), Math.Abs(upper + arr[i] - k));
  
            // if abs value is smaller than smallest
            // update smallest and reset count to 1
            if (curr_min < smallest)
            {
                smallest = curr_min;
                count = 1;
            }
            // if abs value is equal to smallest
            // increment count value
            else if (curr_min == smallest)
            {
                count++;
            }
            s.Add(arr[i]);
        }
  
        // print result
        Console.WriteLine("Minimal Value = " + smallest);
        Console.WriteLine("Total Pairs = " + count);
    }
  
    // driver program
    static void Main(string[] args)
    {
        int[] arr = { 3, 5, 7, 5, 1, 9, 9 };
        int k = 12;
        int n = arr.Length;
        pairs(arr, n, k);
    }
}
 
 
Output
Minimal Value = 0  Total Pairs = 4

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



Next Article
Special two digit numbers in a Binary Search Tree
https://media.geeksforgeeks.org/auth/avatar.png
GeeksforGeeks
Improve
Article Tags :
  • Arrays
  • Binary Search Tree
  • DSA
  • cpp-set
  • Self-Balancing-BST
Practice Tags :
  • Arrays
  • Binary Search Tree

Similar Reads

  • Binary Search Tree
    A Binary Search Tree (or BST) is a data structure used in computer science for organizing and storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right chi
    3 min read
  • Introduction to Binary Search Tree
    Binary Search Tree is a data structure used in computer science for organizing and storing data in a sorted manner. Binary search tree follows all properties of binary tree and for every nodes, its left subtree contains values less than the node and the right subtree contains values greater than the
    3 min read
  • Applications of BST
    Binary Search Tree (BST) is a data structure that is commonly used to implement efficient searching, insertion, and deletion operations along with maintaining sorted sequence of data. Please remember the following properties of BSTs before moving forward. The left subtree of a node contains only nod
    2 min read
  • Applications, Advantages and Disadvantages of Binary Search Tree
    A Binary Search Tree (BST) is a data structure used to storing data in a sorted manner. Each node in a Binary Search Tree has at most two children, a left child and a right child, with the left child containing values less than the parent node and the right child containing values greater than the p
    2 min read
  • Insertion in Binary Search Tree (BST)
    Given a BST, the task is to insert a new node in this BST. Example: How to Insert a value in a Binary Search Tree:A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is f
    15+ min read
  • Searching in Binary Search Tree (BST)
    Given a BST, the task is to search a node in this BST. For searching a value in BST, consider it as a sorted array. Now we can easily perform search operation in BST using Binary Search Algorithm. Input: Root of the below BST Output: TrueExplanation: 8 is present in the BST as right child of rootInp
    7 min read
  • Deletion in Binary Search Tree (BST)
    Given a BST, the task is to delete a node in this BST, which can be broken down into 3 scenarios: Case 1. Delete a Leaf Node in BST Case 2. Delete a Node with Single Child in BST Deleting a single child node is also simple in BST. Copy the child to the node and delete the node. Case 3. Delete a Node
    10 min read
  • Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
    Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree.  Input:  Output: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 100 Input:  Output:
    11 min read
  • Balance a Binary Search Tree
    Given a BST (Binary Search Tree) that may be unbalanced, the task is to convert it into a balanced BST that has the minimum possible height. Examples: Input: Output: Explanation: The above unbalanced BST is converted to balanced with the minimum possible height. Input: Output: Explanation: The above
    10 min read
  • Self-Balancing Binary Search Trees
    Self-Balancing Binary Search Trees are height-balanced binary search trees that automatically keep the height as small as possible when insertion and deletion operations are performed on the tree. The height is typically maintained in order of logN so that all operations take O(logN) time on average
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences