Sum of elements in 1st array such that number of elements less than or equal to them in 2nd array is maximum
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 <iostream>
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[0]);
int n = sizeof(arr2) / sizeof(arr2[0]);
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
<?php
// PHP implementation of the approach
$MAX = 10000;
// Function to return the required sum
function findSumofEle($arr1, $m, $arr2, $n)
{
// Creating hash array initially
// filled with zero
$hash = array_fill(0, $GLOBALS['MAX'], 0);
// Calculate the frequency
// of elements of arr2[]
for ($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 ($i = 1; $i < $GLOBALS['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[]
$maximumFreq = 0;
for ($i = 0; $i < $m; $i++)
$maximumFreq = max($maximumFreq,
$hash[$arr1[$i]]);
// Calculate the sum of elements from arr1[]
// corresponding to maximum frequency
$sumOfElements = 0;
for ($i = 0; $i < $m; $i++)
$sumOfElements += ($maximumFreq == $hash[$arr1[$i]]) ?
$arr1[$i] : 0;
// Return the required sum
return $sumOfElements;
}
// Driver code
$arr1 = array( 2, 5, 6, 8 );
$arr2 = array( 4, 10 );
$m = count($arr1);
$n = count($arr2);
echo findSumofEle($arr1, $m, $arr2, $n);
// This code is contributed by Ryuga
?>
JavaScript
<script>
// Javascript implementation of the approach
// Function to return the required sum
function findSumofEle(arr1, m, arr2, n)
{
let MAX = 100000;
// Creating hash array initially
// filled with zero
let hash = new Array(MAX);
for(let i = 0; i < MAX; i++)
hash[i] = 0;
// Calculate the frequency
// of elements of arr2[]
for(let 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(let 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[]
let maximumFreq = 0;
for(let i = 0; i < m; i++)
{
maximumFreq = Math.max(maximumFreq,
hash[arr1[i]]);
}
// Calculate the sum of elements from arr1[]
// corresponding to maximum frequency
let sumOfElements = 0;
for(let i = 0; i < m; i++)
{
if (maximumFreq == hash[arr1[i]])
sumOfElements += arr1[i];
}
// Return the required sum
return sumOfElements;
}
// Driver code
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));
// This code is contributed by mohit kumar 29
</script>
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 <bits/stdc++.h>
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;i<m;i++)
{
// find the index of first element
// in arr2 which is greater than
// current element in arr1
int y = lower_bound(arr2,arr2+n,arr1[i]+1)-arr2;
// 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
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[0]);
int n = sizeof(arr2) / sizeof(arr2[0]);
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;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;
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<m;i++)
{
// find the index of first element
// in arr2 which is greater than
// current element in arr1
var 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
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
Time Complexity: O(n*log(n)+m*log(n)) where m and n are size of the array.
Auxiliary Space: O(1)
Similar Reads
Maximize the number of indices such that element is greater than element to its left
Given an array arr[] of N integers, the task is to maximize the number of indices such that an element is greater than the element to its left, i.e. arr[i+1] > arr[i] after rearranging the array.Examples: Input: arr[] = {200, 100, 100, 200} Output: 2 Explanation: By arranging the array in followi
6 min read
For each element in 1st array count elements less than or equal to it in 2nd array | Set 2
Given two unsorted arrays arr1[] and arr2[]. They may contain duplicates. For each element in arr1[] count elements less than or equal to it in array arr2[]. Examples: Input : arr1[] = [1, 2, 3, 4, 7, 9] arr2[] = [0, 1, 2, 1, 1, 4] Output : [4, 5, 5, 6, 6, 6] Explanation: There are 4 elements less t
13 min read
Find an element in array such that sum of left array is equal to sum of right array
Given, an array of size n. Find an element that divides the array into two sub-arrays with equal sums. Examples: Input: 1 4 2 5 0Output: 2Explanation: If 2 is the partition, subarrays are : [1, 4] and [5] Input: 2 3 4 1 4 5Output: 1Explanation: If 1 is the partition, Subarrays are : [2, 3, 4] and [4
15+ min read
Maximum elements that can be removed from front of two arrays such that their sum is at most K
Given an integer K and two arrays A[] and B[] consisting of N and M integers, the task is to maximize the number of elements that can be removed from the front of either array according to the following rules: Remove an element from the front of either array A[] and B[] such that the value of the re
15+ min read
Choose two elements from the given array such that their sum is not present in any of the arrays
Given two arrays A[] and B[], the task is to choose two elements X and Y such that X belongs to A[] and Y belongs to B[] and (X + Y) must not be present in any of the array.Examples: Input: A[] = {3, 2, 2}, B[] = {1, 5, 7, 7, 9} Output: 3 9 3 + 9 = 12 and 12 is not present in any of the given arrays
5 min read
Number of indices pair such that element pair sum from first Array is greater than second Array
Given two integer arrays A[] and B[] of equal sizes, the task is to find the number of pairs of indices {i, j} in the arrays such that A[i] + A[j] > B[i] + B[j] and i < j.Examples: Input: A[] = {4, 8, 2, 6, 2}, B[] = {4, 5, 4, 1, 3} Output: 7 Explanation: There are a total of 7 pairs of indice
15+ min read
For each in 1st array count less than or equal to it in 2nd array
You are given two unsorted arrays a[] and b[]. Both arrays may contain duplicate elements. For each element in a[], your task is to count how many elements in b[] are less than or equal to that element.Examples:Input: a[] = [1, 2, 3, 4, 7, 9], b = [0, 1, 2, 1, 1, 4]Output: [4, 5, 5, 6, 6, 6]Explanat
15+ min read
Count of pairs from arrays A and B such that element in A is greater than element in B at that index
Given two arrays A[] and B[] of size N, the task is to count the maximum number of pairs, where each pair contains one from each array, such that A[i] > B[i]. Also the array A can be rearranged any number of times. Examples: Input: A[] = {20, 30, 50}, B[]= {60, 40, 25} Output: 2 Explanation: Init
7 min read
Check if X and Y elements can be selected from two arrays respectively such that the maximum in X is less than the minimum in Y
Given two arrays arr1[] and arr2[] consisting of N and M integers respectively, and two integers X and Y, the task is to check if it is possible to choose X elements from arr1[] and Y elements from arr2[] such that the largest among these X elements is less than the minimum element among these Y ele
15 min read
Maximum number of elements from an array B[] that are present in ranges [A[i] + K, A[i] - K]
Given two arrays A[] of size N and B[] of size M and an integer K, the task is to select at most one element from array B[] for every element A[i] such that the element lies in the range [A[i] - K, A[i] + K] ( for 0 <= i <= N - 1 ). Print the maximum number of elements that can be selected fro
7 min read