Sum of elements in 1 st array such that number of elements less than or equal to them in 2 nd array is maximum | C ++ 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
#include <iostream> NEW_LINE using namespace std ; #define MAX  100000 NEW_LINE int findSumofEle ( int arr1 [ ] , int m , int arr2 [ ] , int n ) { int hash [ MAX ] = { 0 } ; for ( int i = 0 ; i < n ; i ++ ) hash [ arr2 [ i ] ] ++ ; for ( int i = 1 ; i < MAX ; i ++ ) hash [ i ] = hash [ i ] + hash [ i - 1 ] ; int maximumFreq = 0 ; for ( int i = 0 ; i < m ; i ++ ) maximumFreq = max ( maximumFreq , hash [ arr1 [ i ] ] ) ; int sumOfElements = 0 ; for ( int i = 0 ; i < m ; i ++ ) sumOfElements += ( maximumFreq == hash [ arr1 [ i ] ] ) ? arr1 [ i ] : 0 ; return sumOfElements ; } int main ( ) { int arr1 [ ] = { 2 , 5 , 6 , 8 } ; int arr2 [ ] = { 4 , 10 } ; int m = sizeof ( arr1 ) / sizeof ( arr1 [ 0 ] ) ; int n = sizeof ( arr2 ) / sizeof ( arr2 [ 0 ] ) ; cout << findSumofEle ( arr1 , m , arr2 , n ) ; return 0 ; }