Sum of elements in 1 st array such that number of elements less than or equal to them in 2 nd array is maximum | 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
function findSumofEle ( arr1 , m , arr2 , n ) { let MAX = 100000 ; let hash = new Array ( MAX ) ; for ( let i = 0 ; i < MAX ; i ++ ) hash [ i ] = 0 ; for ( let i = 0 ; i < n ; i ++ ) hash [ arr2 [ i ] ] ++ ; for ( let i = 1 ; i < MAX ; i ++ ) hash [ i ] = hash [ i ] + hash [ i - 1 ] ; let maximumFreq = 0 ; for ( let i = 0 ; i < m ; i ++ ) { maximumFreq = Math . max ( maximumFreq , hash [ arr1 [ i ] ] ) ; } let sumOfElements = 0 ; for ( let i = 0 ; i < m ; i ++ ) { if ( maximumFreq == hash [ arr1 [ i ] ] ) sumOfElements += arr1 [ i ] ; } return sumOfElements ; } let arr1 = [ 2 , 5 , 6 , 8 ] ; let arr2 = [ 4 , 10 ] ; let m = arr1 . length ; let n = arr2 . length ; document . write ( findSumofEle ( arr1 , m , arr2 , n ) ) ;