Sum of elements in 1 st array such that number of elements less than or equal to them in 2 nd array is maximum | PHP implementation of the approach ; Function to return the required sum ; Creating hash array initially filled with zero ; Calculate the frequency of elements of arr2 [ ] ; Running sum of hash array such that hash [ i ] will give count of elements less than or equal to i in arr2 [ ] ; To store the maximum value of the number of elements in arr2 [ ] which are smaller than or equal to some element of arr1 [ ] ; Calculate the sum of elements from arr1 [ ] corresponding to maximum frequency ; Return the required sum ; Driver code
< ? php $ MAX = 10000 ; function findSumofEle ( $ arr1 , $ m , $ arr2 , $ n ) { $ hash = array_fill ( 0 , $ GLOBALS [ ' MAX ' ] , 0 ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ hash [ $ arr2 [ $ i ] ] ++ ; for ( $ i = 1 ; $ i < $ GLOBALS [ ' MAX ' ] ; $ i ++ ) $ hash [ $ i ] = $ hash [ $ i ] + $ hash [ $ i - 1 ] ; $ maximumFreq = 0 ; for ( $ i = 0 ; $ i < $ m ; $ i ++ ) $ maximumFreq = max ( $ maximumFreq , $ hash [ $ arr1 [ $ i ] ] ) ; $ sumOfElements = 0 ; for ( $ i = 0 ; $ i < $ m ; $ i ++ ) $ sumOfElements += ( $ maximumFreq == $ hash [ $ arr1 [ $ i ] ] ) ? $ arr1 [ $ i ] : 0 ; return $ sumOfElements ; } $ arr1 = array ( 2 , 5 , 6 , 8 ) ; $ arr2 = array ( 4 , 10 ) ; $ m = count ( $ arr1 ) ; $ n = count ( $ arr2 ) ; echo findSumofEle ( $ arr1 , $ m , $ arr2 , $ n ) ; ? >