Closest value to K from an unsorted array
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 = 6
Output: 7
Explanation:
The absolute difference between 4 and 6 is |4 – 6| = 2
The absolute difference between 2 and 6 is |2 – 6| = 4
The absolute difference between 8 and 6 is |8– 6| = 2
The absolute difference between 11 and 6 is |11 – 6| = 5
The absolute difference between 7 and 6 is |7 – 6| = 1
Here, 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 = 300
Output: 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.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int clostVal( int arr[],
int N,
int K)
{
int res = arr[0];
for ( int i = 1; i < N;
i++) {
if ( abs (K - res) > abs (K - arr[i])) {
res = arr[i];
}
}
return res;
}
int main()
{
int arr[] = { 100, 200, 400 };
int K = 300;
int N = sizeof (arr) / sizeof (arr[0]);
cout << clostVal(arr, N, K);
}
|
Java
import java.io.*;
class GFG{
static int clostVal( int arr[], int N,
int K)
{
int res = arr[ 0 ];
for ( int i = 1 ; i < N; i++)
{
if (Math.abs(K - res) >
Math.abs(K - arr[i]))
{
res = arr[i];
}
}
return res;
}
public static void main (String[] args)
{
int arr[] = { 100 , 200 , 400 };
int K = 300 ;
int N = arr.length;
System.out.print(clostVal(arr, N, K));
}
}
|
Python3
def clostVal(arr, N, K):
res = arr[ 0 ]
for i in range ( 1 , N, 1 ):
if ( abs (K - res) >
abs (K - arr[i])):
res = arr[i]
return res
arr = [ 100 , 200 , 400 ]
K = 300
N = len (arr)
print (clostVal(arr, N, K))
|
C#
using System;
class GFG{
static int clostVal( int [] arr, int N,
int K)
{
int res = arr[0];
for ( int i = 1; i < N; i++)
{
if (Math.Abs(K - res) >
Math.Abs(K - arr[i]))
{
res = arr[i];
}
}
return res;
}
public static void Main ()
{
int [] arr = { 100, 200, 400 };
int K = 300;
int N = arr.Length;
Console.WriteLine(clostVal(arr, N, K));
}
}
|
Javascript
<script>
function clostVal(arr, N, K)
{
let res = arr[0];
for (let i = 1; i < N; i++)
{
if (Math.abs(K - res) >
Math.abs(K - arr[i]))
{
res = arr[i];
}
}
return res;
}
let arr = [ 100, 200, 400 ];
let K = 300;
let N = arr.length;
document.write(clostVal(arr, N, K));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Last Updated :
05 May, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...