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 is not more than k ; Return result ; Driver code
< ? php function findSumofEle ( $ arr1 , $ m , $ arr2 , $ n , $ k ) { $ arraySum = 0 ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ arraySum += $ arr2 [ $ i ] ; $ mean = $ arraySum / $ n ; $ sumOfElements = 0 ; for ( $ 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 ; } $ arr1 = array ( 1 , 2 , 3 , 4 , 7 , 9 ) ; $ arr2 = array ( 0 , 1 , 2 , 1 , 1 , 4 ) ; $ k = 2 ; $ m = count ( $ arr1 ) ; $ n = count ( $ arr2 ) ; print ( findSumofEle ( $ arr1 , $ m , $ arr2 , $ n , $ k ) ) ; ? >