Count elements in first Array with absolute difference greater than K with an element in second Array | C ++ program to count elements in first Array with absolute difference greater than K with an element in second Array ; Function to count the such elements ; Store count of required elements in arr1 ; Initialise the smallest and the largest value from the second array arr2 [ ] ; Find the smallest and the largest element in arr2 ; Check if absolute difference of smallest and arr1 [ i ] or largest and arr1 [ i ] is > K then arr [ i ] is a required element ; Print the final result ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void countDist ( int arr1 [ ] , int n , int arr2 [ ] , int m , int k ) { int count = 0 ; int smallest = arr2 [ 0 ] ; int largest = arr2 [ 0 ] ; for ( int i = 0 ; i < m ; i ++ ) { smallest = max ( smallest , arr2 [ i ] ) ; largest = min ( largest , arr1 [ i ] ) ; } for ( int i = 0 ; i < n ; i ++ ) { if ( abs ( arr1 [ i ] - smallest ) > k || abs ( arr1 [ i ] - largest ) > k ) count ++ ; } cout << count ; } int main ( ) { int arr1 [ ] = { 3 , 1 , 4 } ; int n = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int arr2 [ ] = { 5 , 1 , 2 } ; int m = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; int k = 2 ; countDist ( arr1 , n , arr2 , m , k ) ; return 0 ; }