Sum of elements in an array whose difference with the mean of another array is less than k | 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
function findSumofEle ( arr1 , m , arr2 , n , k ) { var arraySum = 0 ; for ( var i = 0 ; i < n ; i ++ ) arraySum += arr2 [ i ] ; var mean = ( arraySum / n ) ; var sumOfElements = 0 ; var difference ; for ( var 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 ; } var arr1 = [ 1 , 2 , 3 , 4 , 7 , 9 ] ; var arr2 = [ 0 , 1 , 2 , 1 , 1 , 4 ] ; var k = 2 ; var m , n ; m = arr1 . length ; n = arr2 . length ; document . write ( findSumofEle ( arr1 , m , arr2 , n , k ) ) ;