 Open in App
Not now

# Sum of elements in 1st array such that number of elements less than or equal to them in 2nd array is maximum

• Difficulty Level : Easy
• Last Updated : 29 Aug, 2022

Given two unsorted arrays arr1[] and arr2[], the task is to find the sum of elements of arr1[] such that the number of elements less than or equal to them in arr2[] is maximum.

Examples:

Input: arr1[] = {1, 2, 3, 4, 7, 9}, arr2[] = {0, 1, 2, 1, 1, 4}
Output: 20
Below table shows the count of elements in arr2[] which are ≤ the elements of arr1[]

Count for 4, 7 and 9 is maximum.
Hence, the resultant sum is 4 + 7 + 9 = 20.
Input:arr1[] = {5, 10, 2, 6, 1, 8, 6, 12}, arr2[] = {6, 5, 11, 4, 2, 3, 7}
Output: 12

Approach: The idea behind an efficient solution for the above problem is to use hashing of the second array and then find the cumulative sum of a hashed array. After that, the count of elements in the second array less than or equal to elements of 1st array can easily be calculated. This will give a frequency array which represents the count of elements in the second array less than or equal to elements of 1st array from where the sum of elements of the first array can be calculated corresponding to the maximum frequency in the frequency array.

Below is the implementation of the above approach:

## C++

 `// C++ implementation of the approach``#include ``using` `namespace` `std;``#define MAX 100000` `// Function to return the required sum``int` `findSumofEle(``int` `arr1[], ``int` `m,``                 ``int` `arr2[], ``int` `n)``{``    ``// Creating hash array initially``    ``// filled with zero``    ``int` `hash[MAX] = { 0 };` `    ``// Calculate the frequency``    ``// of elements of arr2[]``    ``for` `(``int` `i = 0; i < n; i++)``        ``hash[arr2[i]]++;` `    ``// Running sum of hash array``    ``// such that hash[i] will give count of``    ``// elements less than or equal to i in arr2[]``    ``for` `(``int` `i = 1; i < MAX; i++)``        ``hash[i] = hash[i] + hash[i - 1];` `    ``// To store the maximum value of``    ``// the number of elements in arr2[] which are``    ``// smaller than or equal to some element of arr1[]``    ``int` `maximumFreq = 0;``    ``for` `(``int` `i = 0; i < m; i++)``        ``maximumFreq = max(maximumFreq, hash[arr1[i]]);` `    ``// Calculate the sum of elements from arr1[]``    ``// corresponding to maximum frequency``    ``int` `sumOfElements = 0;``    ``for` `(``int` `i = 0; i < m; i++)``        ``sumOfElements += (maximumFreq == hash[arr1[i]]) ? arr1[i] : 0;` `    ``// Return the required sum``    ``return` `sumOfElements;``}` `// Driver code``int` `main()``{``    ``int` `arr1[] = { 2, 5, 6, 8 };``    ``int` `arr2[] = { 4, 10 };``    ``int` `m = ``sizeof``(arr1) / ``sizeof``(arr1);``    ``int` `n = ``sizeof``(arr2) / ``sizeof``(arr2);` `    ``cout << findSumofEle(arr1, m, arr2, n);` `    ``return` `0;``}`

## Java

 `// Java implementation of the approach` `class` `GFG``{` `    ``static` `int` `MAX = ``100000``;` `    ``// Function to return the required sum``    ``static` `int` `findSumofEle(``int` `arr1[], ``int` `m,``                            ``int` `arr2[], ``int` `n)``    ``{``        ``// Creating hash array initially``        ``// filled with zero``        ``int` `hash[] = ``new` `int``[MAX];` `        ``// Calculate the frequency``        ``// of elements of arr2[]``        ``for` `(``int` `i = ``0``; i < n; i++)``        ``{``            ``hash[arr2[i]]++;``        ``}` `        ``// Running sum of hash array``        ``// such that hash[i] will give count of``        ``// elements less than or equal to i in arr2[]``        ``for` `(``int` `i = ``1``; i < MAX; i++)``        ``{``            ``hash[i] = hash[i] + hash[i - ``1``];``        ``}` `        ``// To store the maximum value of``        ``// the number of elements in arr2[] which are``        ``// smaller than or equal to some element of arr1[]``        ``int` `maximumFreq = ``0``;``        ``for` `(``int` `i = ``0``; i < m; i++)``        ``{``            ``maximumFreq = Math.max(maximumFreq, hash[arr1[i]]);``        ``}` `        ``// Calculate the sum of elements from arr1[]``        ``// corresponding to maximum frequency``        ``int` `sumOfElements = ``0``;``        ``for` `(``int` `i = ``0``; i < m; i++)``        ``{``            ``sumOfElements += (maximumFreq == hash[arr1[i]]) ? arr1[i] : ``0``;``        ``}` `        ``// Return the required sum``        ``return` `sumOfElements;``    ``}` `    ``// Driver code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``int` `arr1[] = {``2``, ``5``, ``6``, ``8``};``        ``int` `arr2[] = {``4``, ``10``};``        ``int` `m = arr1.length;``        ``int` `n = arr2.length;` `        ``System.out.println(findSumofEle(arr1, m, arr2, n));``    ``}``}` `// This code has been contributed by 29AjayKumar`

## Python3

 `# Python 3 implementation of the approach``MAX` `=` `100000` `# Function to return the required sum``def` `findSumofEle(arr1, m, arr2, n):``    ` `    ``# Creating hash array initially``    ``# filled with zero``    ``hash` `=` `[``0` `for` `i ``in` `range``(``MAX``)]` `    ``# Calculate the frequency``    ``# of elements of arr2[]``    ``for` `i ``in` `range``(n):``        ``hash``[arr2[i]] ``+``=` `1` `    ``# Running sum of hash array``    ``# such that hash[i] will give count of``    ``# elements less than or equal to i in arr2[]``    ``for` `i ``in` `range``(``1``, ``MAX``, ``1``):``        ``hash``[i] ``=` `hash``[i] ``+` `hash``[i ``-` `1``]` `    ``# To store the maximum value of``    ``# the number of elements in arr2[]``    ``# which are smaller than or equal``    ``# to some element of arr1[]``    ``maximumFreq ``=` `0``    ``for` `i ``in` `range``(m):``        ``maximumFreq ``=` `max``(maximumFreq,``                          ``hash``[arr1[i]])` `    ``# Calculate the sum of elements from arr1[]``    ``# corresponding to maximum frequency``    ``sumOfElements ``=` `0``    ``for` `i ``in` `range``(m):``        ``if` `(maximumFreq ``=``=` `hash``[arr1[i]]):``            ``sumOfElements ``+``=` `arr1[i]` `    ``# Return the required sum``    ``return` `sumOfElements` `# Driver code``if` `__name__ ``=``=` `'__main__'``:``    ``arr1 ``=` `[``2``, ``5``, ``6``, ``8``]``    ``arr2 ``=` `[``4``, ``10``]``    ``m ``=` `len``(arr1)``    ``n ``=` `len``(arr2)``    ``print``(findSumofEle(arr1, m, arr2, n))` `# This code is contributed by``# Surendra_Gangwar`

## C#

 `// C# implementation of the approach``using` `System;` `class` `GFG``{` `    ``static` `int` `MAX = 100000;` `    ``// Function to return the required sum``    ``static` `int` `findSumofEle(``int``[] arr1, ``int` `m,``                            ``int``[] arr2, ``int` `n)``    ``{``        ``// Creating hash array initially``        ``// filled with zero``        ``int``[] hash = ``new` `int``[MAX];` `        ``// Calculate the frequency``        ``// of elements of arr2[]``        ``for` `(``int` `i = 0; i < n; i++)``        ``{``            ``hash[arr2[i]]++;``        ``}` `        ``// Running sum of hash array``        ``// such that hash[i] will give count of``        ``// elements less than or equal to i in arr2[]``        ``for` `(``int` `i = 1; i < MAX; i++)``        ``{``            ``hash[i] = hash[i] + hash[i - 1];``        ``}` `        ``// To store the maximum value of``        ``// the number of elements in arr2[] which are``        ``// smaller than or equal to some element of arr1[]``        ``int` `maximumFreq = 0;``        ``for` `(``int` `i = 0; i < m; i++)``        ``{``            ``maximumFreq = Math.Max(maximumFreq, hash[arr1[i]]);``        ``}` `        ``// Calculate the sum of elements from arr1[]``        ``// corresponding to maximum frequency``        ``int` `sumOfElements = 0;``        ``for` `(``int` `i = 0; i < m; i++)``        ``{``            ``sumOfElements += (maximumFreq == hash[arr1[i]]) ? arr1[i] : 0;``        ``}` `        ``// Return the required sum``        ``return` `sumOfElements;``    ``}` `    ``// Driver code``    ``public` `static` `void` `Main()``    ``{``        ``int``[] arr1 = {2, 5, 6, 8};``        ``int``[] arr2 = {4, 10};``        ``int` `m = arr1.Length;``        ``int` `n = arr2.Length;` `        ``Console.WriteLine(findSumofEle(arr1, m, arr2, n));``    ``}``}` `// This code has been contributed by Code_Mech.`

## PHP

 ``

## Javascript

 ``

Output

`19`

Time Complexity: O(MAX)
Auxiliary Space: O(MAX), since MAX extra space has been taken.

Another efficient approach: Using Standard Template Library (STL)
In this approach, we will first sort the 2nd array. Then we will iterate in the first array and for each element in the first array, we will find the count of smaller elements in arr2 using lower_bound STL in O(log(n)) time. If the count of such elements is maximum then we can say that the corresponding element in arr1 will be in the answer. In this way, we keep on iterating in the 1st array and try to find the elements with the maximum count in the 2nd array and we will add those elements to the answer. The time complexity of this approach is O(n*log(n)+m*log(n)) and hence it is better than the previous approach for small values of n and m. Also, the auxiliary space in this approach is O(1) which is better than the previous approach.

Below is the implementation of the above approach:

## C++

 `// C++ implementation of the approach``#include ``using` `namespace` `std;` `// Function to return the required sum``int` `findSumofEle(``int` `arr1[], ``int` `m, ``int` `arr2[], ``int` `n)``{``    ``// Variable to store the``    ``// maximum count of numbers``    ``// which are smaller than``    ``// any element``    ``int` `maxi=INT_MIN;``    ``// Variable to store the answer``    ``int` `ans=0;``    ``sort(arr2,arr2+n);``    ``for``(``int` `i=0;imaxi)``        ``{``            ``maxi=y;``            ``ans=arr1[i];``        ``}``        ``// if count of all such element is``        ``// equal to highest for this element``        ``// in arr1 then add this element also in answer``        ``else` `if``(y==maxi)``        ``{``            ``ans+=arr1[i];``        ``}``    ``}``    ``// Return the answer``    ``return` `ans;``}` `// Driver code``int` `main()``{``    ``int` `arr1[] = {5, 10, 2, 6, 1, 8, 6, 12};``    ``int` `arr2[] = { 6, 5, 11, 4, 2, 3, 7};``    ``int` `m = ``sizeof``(arr1) / ``sizeof``(arr1);``    ``int` `n = ``sizeof``(arr2) / ``sizeof``(arr2);` `    ``cout << findSumofEle(arr1, m, arr2, n);` `    ``return` `0;``}` `// This code is contributed by Pushpesh Raj`

## Java

 `// Java implementation of the approach``import` `java.util.*;` `class` `GFG {``  ``static` `int` `lower_bound(``int``[] arr, ``int` `elem)``  ``{``    ``for` `(``int` `i = ``0``; i < arr.length; i++)``      ``if` `(elem <= arr[i])``        ``return` `i;``    ``return` `arr.length;``  ``}` `  ``// Function to return the required sum``  ``static` `int` `findSumofEle(``int``[] arr1, ``int` `m, ``int``[] arr2,``                          ``int` `n)``  ``{``    ``// Variable to store the``    ``// maximum count of numbers``    ``// which are smaller than``    ``// any element``    ``int` `maxi = Integer.MIN_VALUE;` `    ``// Variable to store the answer``    ``int` `ans = ``0``;``    ``Arrays.sort(arr2);``    ``for` `(``int` `i = ``0``; i < m; i++)``    ``{` `      ``// find the index of first element``      ``// in arr2 which is greater than``      ``// current element in arr1``      ``int` `y = lower_bound(arr2, arr1[i] + ``1``);` `      ``// subtracting 1 to get the count of all smaller``      ``// elements``      ``y = y - ``1``;` `      ``// if the count of all such element``      ``// is highest for this element in arr1``      ``// then it will be the answer``      ``if` `(y > maxi) {``        ``maxi = y;``        ``ans = arr1[i];``      ``}` `      ``// if count of all such element is``      ``// equal to highest for this element``      ``// in arr1 then add this element also in answer``      ``else` `if` `(y == maxi) {``        ``ans += arr1[i];``      ``}``    ``}` `    ``// Return the answer``    ``return` `ans;``  ``}` `  ``// Driver code``  ``public` `static` `void` `main(String[] args)``  ``{``    ``int``[] arr1 = { ``5``, ``10``, ``2``, ``6``, ``1``, ``8``, ``6``, ``12` `};``    ``int``[] arr2 = { ``6``, ``5``, ``11``, ``4``, ``2``, ``3``, ``7` `};``    ``int` `m = arr1.length;``    ``int` `n = arr2.length;` `    ``System.out.println(findSumofEle(arr1, m, arr2, n));``  ``}``}` `// This code is contributed by phasing17`

## Python3

 `# Python3 implementation of the approach``def` `lower_bound(arr, n, elem):``    ``for` `i ``in` `range``(n):``        ``if` `(arr[i] >``=` `elem):``            ``return` `i;``    ``return` `n;``    ` `# function to return the required sum``def` `findSumofEle(arr1, m, arr2, n):` `    ``# Variable to store the``    ``# maximum count of numbers``    ``# which are smaller than``    ``# any element``    ``maxi``=` `-``1000000``;``    ``# Variable to store the answer``    ``ans``=``0``;``    ``arr2.sort();``    ` `    ``for` `i ``in` `range``(m):``    ` `        ``# find the index of first element``        ``# in arr2 which is greater than``        ``# current element in arr1``        ``y ``=` `lower_bound(arr2, n, arr1[i]``+``1``);``        ` `        ``# subtracting 1 to get the count of all smaller``        ``# elements``        ``y ``=` `y ``-` `1``;``        ` `        ``# if the count of all such element``        ``# is highest for this element in arr1``        ``# then it will be the answer``        ``if``(y > maxi):``            ``maxi ``=` `y;``            ``ans ``=` `arr1[i];``        ` `        ``# if count of all such element is``        ``# equal to highest for this element``        ``# in arr1 then add this element also in answer``        ``elif``(y``=``=``maxi):``            ``ans``+``=``arr1[i];``    ` `    ` `    ``# Return the answer``    ``return` `ans;` `# Driver code``arr1 ``=` `[``5``, ``10``, ``2``, ``6``, ``1``, ``8``, ``6``, ``12``];``arr2 ``=` `[ ``6``, ``5``, ``11``, ``4``, ``2``, ``3``, ``7``];``m ``=` `len``(arr1);``n ``=` `len``(arr2)` `print``(findSumofEle(arr1, m, arr2, n));` `# This code is contributed by phasing17`

## C#

 `// C# implementation of the approach` `using` `System;``using` `System.Collections.Generic;` `class` `GFG``{``    ``static` `int` `lower_bound(``int``[] arr, ``int` `elem)``    ``{``        ``for` `(``int` `i = 0; i < arr.Length; i++)``            ``if` `(elem <= arr[i])``                ``return` `i;``        ``return` `arr.Length;``    ``}``    ``// Function to return the required sum``    ``static` `int` `findSumofEle(``int``[] arr1, ``int` `m, ``int``[] arr2, ``int` `n)``    ``{``        ``// Variable to store the``        ``// maximum count of numbers``        ``// which are smaller than``        ``// any element``        ``int` `maxi= Int32.MinValue;``        ``// Variable to store the answer``        ``int` `ans=0;``        ``Array.Sort(arr2);``        ``for``(``int` `i=0;imaxi)``            ``{``                ``maxi=y;``                ``ans=arr1[i];``            ``}``            ``// if count of all such element is``            ``// equal to highest for this element``            ``// in arr1 then add this element also in answer``            ``else` `if``(y==maxi)``            ``{``                ``ans+=arr1[i];``            ``}``        ``}``        ``// Return the answer``        ``return` `ans;``    ``}``    ` `    ``// Driver code``    ``public` `static` `void` `Main(``string``[] args)``    ``{``        ``int``[] arr1 = {5, 10, 2, 6, 1, 8, 6, 12};``        ``int``[] arr2 = { 6, 5, 11, 4, 2, 3, 7};``        ``int` `m = arr1.Length;``        ``int` `n = arr2.Length;``    ` `        ``Console.WriteLine(findSumofEle(arr1, m, arr2, n));``    ` `    ``}``}` `// This code is contributed by phasing17`

## Javascript

 `// JavaScript implementation of the approach``function` `lower_bound(arr, n, elem)``{``    ``for` `(``var` `i = 0; i < n; i++)``        ``if` `(arr[i] >= elem)``            ``return` `i;``    ``return` `n;``    ` `}` `// Function to return the required sum``function` `findSumofEle(arr1, m, arr2, n)``{``    ``// Variable to store the``    ``// maximum count of numbers``    ``// which are smaller than``    ``// any element``    ``let maxi= -1000000;``    ``// Variable to store the answer``    ``let ans=0;``    ``arr2.sort();``    ` `    ``for``(``var` `i=0;i maxi)``        ``{``            ``maxi = y;``            ``ans = arr1[i];``        ``}``        ` `        ``// if count of all such element is``        ``// equal to highest for this element``        ``// in arr1 then add this element also in answer``        ``else` `if``(y==maxi)``        ``{``            ``ans+=arr1[i];``        ``}``    ``}``    ` `    ``// Return the answer``    ``return` `ans;``}` `// Driver code``let arr1 = [5, 10, 2, 6, 1, 8, 6, 12];``let arr2 = [ 6, 5, 11, 4, 2, 3, 7];``let m = arr1.length;``let n = arr2.length;` `console.log(findSumofEle(arr1, m, arr2, n));` `// This code is contributed by phasing17`

Output

`12`

Time Complexity: O(n*log(n)+m*log(n)) where m and n are size of the array.
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up