Closest value to K from an unsorted array - GeeksforGeeks

05 May, 2021
Given an array arr[] consisting of N integers and an integer K, the task is to find the array element closest to K. If multiple closest values exist, then print the smallest one.
Examples:
Input: arr[]={4, 2, 8, 11, 7}, K = 6Output: 7Explanation:The absolute difference between 4 and 6 is |4 – 6| = 2The absolute difference between 2 and 6 is |2 – 6| = 4The absolute difference between 8 and 6 is |8– 6| = 2The absolute difference between 11 and 6 is |11 – 6| = 5The absolute difference between 7 and 6 is |7 – 6| = 1Here, the absolute difference between K(=6) and 7 is minimum. Therefore, the closest value of K(=6) is 7
Input: arr[]={100, 200, 400}, K = 300Output: 200
Approach: The idea is to traverse the given array and print an element of the array which gives the minimum absolute difference with the given integer K. Follow the steps below to solve the problem:
Initialize a variable, say res, to store the array element the closest value to K.Traverse the array and compare the absolute value of abs(K – res) and the absolute value of abs(K – arr[i]).If the value of abs(K – res) exceeds abs(K – arr[i]), then update res to arr[i].Finally, print res.
Initialize a variable, say res, to store the array element the closest value to K.
Traverse the array and compare the absolute value of abs(K – res) and the absolute value of abs(K – arr[i]).
If the value of abs(K – res) exceeds abs(K – arr[i]), then update res to arr[i].
Finally, print res.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to get// the closest valueint clostVal(int arr[],             int N,             int K){    // Stores the closest    // value to K    int res = arr[0];     // Traverse the array    for (int i = 1; i < N;         i++) {         // If absolute difference        // of K and res exceeds        // absolute difference of K        // and current element        if (abs(K - res) > abs(K - arr[i])) {            res = arr[i];        }    }     // Return the closest    // array element    return res;} // Driver Codeint main(){    int arr[] = { 100, 200, 400 };    int K = 300;    int N = sizeof(arr) / sizeof(arr[0]);     cout << clostVal(arr, N, K);}
// Java program to implement// the above approachimport java.io.*; class GFG{  // Function to get// the closest valuestatic int clostVal(int arr[], int N,                    int K){         // Stores the closest    // value to K    int res = arr[0];      // Traverse the array    for(int i = 1; i < N; i++)    {                 // If absolute difference        // of K and res exceeds        // absolute difference of K        // and current element        if (Math.abs(K - res) >            Math.abs(K - arr[i]))        {            res = arr[i];        }    }      // Return the closest    // array element    return res;}  // Driver Codepublic static void main (String[] args){    int arr[] = { 100, 200, 400 };    int K = 300;    int N = arr.length;         System.out.print(clostVal(arr, N, K));}} // This code is contributed by code_hunt
# Python3 program to implement# the above approach # Function to get# the closest valuedef clostVal(arr, N, K):         # Stores the closest    # value to K    res = arr[0]     # Traverse the array    for i in range(1, N, 1):         # If absolute difference        # of K and res exceeds        # absolute difference of K        # and current element        if (abs(K - res) >            abs(K - arr[i])):            res = arr[i]     # Return the closest    # array element    return res # Driver Codearr = [ 100, 200, 400 ]K = 300N = len(arr) print(clostVal(arr, N, K)) # This code is contributed by susmitakundugoaldanga
// C# program to implement// the above approach using System; class GFG{  // Function to get// the closest valuestatic int clostVal(int[] arr, int N,                    int K){         // Stores the closest    // value to K    int res = arr[0];      // Traverse the array    for(int i = 1; i < N; i++)    {                 // If absolute difference        // of K and res exceeds        // absolute difference of K        // and current element        if (Math.Abs(K - res) >            Math.Abs(K - arr[i]))        {            res = arr[i];        }    }      // Return the closest    // array element    return res;}  // Driver Codepublic static void Main (){    int[] arr = { 100, 200, 400 };    int K = 300;    int N = arr.Length;         Console.WriteLine(clostVal(arr, N, K));}} // This code is contributed by sanjoy_62
<script> // Javascript program to implement// the above approach // Function to get// the closest valuefunction clostVal(arr, N, K){         // Stores the closest    // value to K    let res = arr[0];      // Traverse the array    for(let i = 1; i < N; i++)    {                 // If absolute difference        // of K and res exceeds        // absolute difference of K        // and current element        if (Math.abs(K - res) >            Math.abs(K - arr[i]))        {            res = arr[i];        }    }      // Return the closest    // array element    return res;} // Driver Code     let arr = [ 100, 200, 400 ];    let K = 300;    let N = arr.length;         document.write(clostVal(arr, N, K)); </script>
200
 
Time Complexity: O(N)Auxiliary Space: O(1)
code_hunt
sanjoy_62
susmitakundugoaldanga
avijitmondal1998
Arrays
Mathematical
School Programming
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Window Sliding Technique
Trapping Rain Water
Reversal algorithm for array rotation
Building Heap from Array
Move all negative numbers to beginning and positive to end with constant extra space
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7