Sum of elements in an array whose difference with the mean of another array is less than k | C ++ implementation of the approach ; Function for finding sum of elements whose diff with mean is not more than k ; Find the mean of second array ; Find sum of elements from array1 whose difference with mean in not more than k ; Return result ; Driver code
#include <iostream> NEW_LINE using namespace std ; int findSumofEle ( int arr1 [ ] , int m , int arr2 [ ] , int n , int k ) { float arraySum = 0 ; for ( int i = 0 ; i < n ; i ++ ) arraySum += arr2 [ i ] ; float mean = arraySum / n ; int sumOfElements = 0 ; float difference ; for ( int i = 0 ; i < m ; i ++ ) { difference = arr1 [ i ] - mean ; if ( ( difference < 0 ) && ( k > ( -1 ) * difference ) ) { sumOfElements += arr1 [ i ] ; } if ( ( difference >= 0 ) && ( k > difference ) ) { sumOfElements += arr1 [ i ] ; } } return sumOfElements ; } int main ( ) { int arr1 [ ] = { 1 , 2 , 3 , 4 , 7 , 9 } ; int arr2 [ ] = { 0 , 1 , 2 , 1 , 1 , 4 } ; int k = 2 ; int m , n ; m = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << findSumofEle ( arr1 , m , arr2 , n , k ) ; return 0 ; }