Kth largest pairwise product possible from given two Arrays
Last Updated :
09 Feb, 2023
Given two arrays arr[] and brr[] containing integers. The task is to find the Kth largest product of a pair (arr[i], brr[j]).
Examples:
Input: arr[] = {1, -2, 3}, brr[] = {3, -4, 0}, K = 3
Output: 3
Explanation: All product combinations in descending order are : [9, 8, 3, 0, 0, 0, -4, -6, -12] and 3rd largest element is 3.
Input: arr[] = {-1, -5, -3}, brr[] = {-3, -4, 0}, K =5
Output: 4
Explanation: All product combinations in descending order are : [20, 15, 12, 9, 4, 3, 0, 0, 0] and 5th largest element is 4.
Naive Approach: Generate all the possible products combination for each element in array arr[] with each element in array brr[]. Then sort the array of results and return the Kth element of the results array.
C++
#include <bits/stdc++.h>
using namespace std;
int solve( int a[ ], int n, int b[ ], int m, int k) {
vector< int > ans;
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < m; j++) {
int prod = a[i] * b[j];
ans.push_back(prod);
}
}
sort(ans.begin(), ans.end(), greater< int >());
return ans[k - 1];
}
int main()
{
int arr[ ] = { 1, -2, 3 };
int brr[ ] = { 3, -4, 0 };
int K = 3;
int n = sizeof (arr) / sizeof ( int );
int m = sizeof (brr) / sizeof ( int );
int val = solve(arr, n, brr, m, K);
cout << val;
return 0;
}
|
Java
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
class GFG {
static int solve( int [] a, int [] b, int k) {
List<Integer> ans = new LinkedList<>();
int n = a.length;
int m = b.length;
for ( int i = 0 ; i < n; i++) {
for ( int j = 0 ; j < m; j++) {
int prod = a[i] * b[j];
ans.add(prod);
}
}
Collections.sort(ans, (x, y) -> y - x);
return (ans.get(k - 1 ));
}
public static void main(String[] args)
{
int [] arr = { 1 , - 2 , 3 };
int [] brr = { 3 , - 4 , 0 };
int K = 3 ;
int val = solve(arr, brr, K);
System.out.println(val);
}
}
|
Python3
def solve(a, b, k):
ans = []
n = len (a)
m = len (b)
for i in range (n):
for j in range (m):
prod = a[i] * b[j]
ans.append(prod)
ans.sort(reverse = True )
return (ans[k - 1 ])
arr = [ 1 , - 2 , 3 ]
brr = [ 3 , - 4 , 0 ]
K = 3
val = solve(arr, brr, K)
print (val)
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static int solve( int [] a, int [] b, int k) {
List< int > ans = new List< int >();
int n = a.Length;
int m = b.Length;
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < m; j++) {
int prod = a[i] * b[j];
ans.Add(prod);
}
}
ans.Sort((x, y) => y - x);
return (ans[k - 1]);
}
public static void Main(String[] args)
{
int [] arr = { 1, -2, 3 };
int [] brr = { 3, -4, 0 };
int K = 3;
int val = solve(arr, brr, K);
Console.WriteLine(val);
}
}
|
Javascript
<script>
function solve(a, b, k)
{
ans = []
n = a.length
m = b.length
for (let i = 0; i < n; i++)
{
for (let j = 0; j < m; j++)
{
prod = a[i] * b[j]
ans.push(prod)
}
}
ans.sort( function (a, b) { return b - a })
return (ans[k - 1])
}
arr = [1, -2, 3]
brr = [3, -4, 0]
K = 3
val = solve(arr, brr, K)
document.write(val)
</script>
|
Time Complexity: O(N*M + (N+M) * Log(N+M))
Auxiliary Space: O(N+M)
Efficient Approach: This problem can be solved by using the Greedy Approach and Heaps. Follow the steps below to solve the given problem.
- Sort the brr[] array.
- Keep larger size array in the array arr[].
- Create a max heap to store the elements with their respective indices.
- Traverse each element from array arr[]. The element can be either positive or negative.
- Positive: Multiply current element from arr[] with the largest element of sorted array brr[]. To ensure that maximum element is obtained.
- Negative: In this case multiply with the smallest value, i.e. with the first element from array brr[]. This is due to the property of negation, as a larger value can be obtained by multiplying with the smallest one.
- Insert three values into heap such that : ( product, i, j ) where i & j are the indices of arrays arr[] and brr[].
- Now run a for loop K times and pop elements from the heap.
- Now check if the value present at arr[i] is positive or negative
- Positive: So next_j = ( current_j – 1) because as max heap is been used, all the higher indices might have been already popped from the heap.
- Negative: next_j = (current_j +1) because all the smaller values yielding larger elements might have been already popped from the heap.
- Finally, return the answer
Note: Max heap is implemented with the help of min-heap, by negating the signs of the values while inserting them into the heap in Python.
Below is the implementation of the above approach.
C++
#include<bits/stdc++.h>
using namespace std;
class Pair {
public :
int val;
int i;
int j;
Pair( int val, int i, int j)
{
this ->val = val;
this ->i = i;
this ->j = j;
}
};
struct comparator {
bool operator()(Pair const & p1, Pair const & p2)
{
return p1.val < p2.val;
}
};
int solve( int * a, int * b, int k)
{
sort(b, b + k);
int n = k;
int m = k;
if (n < m) {
return solve(b, a, k);
}
priority_queue<Pair, vector<Pair>, comparator> heap;
for ( int i = 0; i < n; i++) {
int curr = a[i];
if (curr < 0) {
int val = curr * b[0];
heap.push(Pair(val, i, 0));
}
else
{
int val = curr * b[m - 1];
heap.push(Pair(val, i, m - 1));
}
}
k--;
for ( int i = 0; i < k; i++) {
Pair pair = heap.top();
heap.pop();
int val = pair.val;
int iIndex = pair.i;
int jIndex = pair.j;
int nextJ;
if (a[iIndex] < 0) {
nextJ = jIndex + 1;
}
else
{
nextJ = jIndex - 1;
}
if (nextJ >= 0 && nextJ < m) {
int newVal = a[iIndex] * b[nextJ];
heap.push(Pair(newVal, iIndex, nextJ));
}
}
return heap.top().val;
}
int main()
{
int arr[] = { 1, -2, 3 };
int brr[] = { 3, -4, 0 };
int K = 3;
int val = solve(arr, brr, K);
cout << val << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class Pair {
int val;
int i;
int j;
public Pair( int val, int i, int j)
{
this .val = val;
this .i = i;
this .j = j;
}
}
class GFG {
static int solve( int [] a, int [] b, int k)
{
Arrays.sort(b);
int n = a.length;
int m = b.length;
if (n < m) {
return solve(b, a, k);
}
PriorityQueue<Pair> heap = new PriorityQueue<>(
(p1, p2) -> p2.val - p1.val);
for ( int i = 0 ; i < n; i++) {
int curr = a[i];
if (curr < 0 ) {
int val = curr * b[ 0 ];
heap.add( new Pair(val, i, 0 ));
}
else {
int val = curr * b[m - 1 ];
heap.add( new Pair(val, i, m - 1 ));
}
}
k--;
for ( int i = 0 ; i < k; i++) {
Pair pair = heap.poll();
int val = pair.val;
int iIndex = pair.i;
int jIndex = pair.j;
int nextJ;
if (a[iIndex] < 0 ) {
nextJ = jIndex + 1 ;
}
else {
nextJ = jIndex - 1 ;
}
if (nextJ >= 0 && nextJ < m) {
int newVal = a[iIndex] * b[nextJ];
heap.add( new Pair(newVal, iIndex, nextJ));
}
}
return heap.peek().val;
}
public static void main(String[] args)
{
int [] arr = { 1 , - 2 , 3 };
int [] brr = { 3 , - 4 , 0 };
int K = 3 ;
int val = solve(arr, brr, K);
System.out.println(val);
}
}
|
Python3
from heap import heappush as push, heappop as pop
def solve(a, b, k):
b.sort()
n, m = len (a), len (b)
if (n < m):
return solve(b, a, k)
heap = []
for i in range (n):
curr = a[i]
if (curr < 0 ):
val = curr * b[ 0 ]
push(heap, ( - val, i, 0 ))
else :
val = curr * b[ - 1 ]
push(heap, ( - val, i, m - 1 ))
k = k - 1
for _ in range (k):
val, i, j = pop(heap)
val = - val
if (a[i] < 0 ):
next_j = j + 1
else :
next_j = j - 1
if ( 0 < = next_j < m):
new_val = a[i] * b[next_j]
push(heap, ( - new_val, i, next_j))
return - (heap[ 0 ][ 0 ])
arr = [ 1 , - 2 , 3 ]
brr = [ 3 , - 4 , 0 ]
K = 3
val = solve(arr, brr, K)
print (val)
|
C#
using System;
using System.Collections.Generic;
class Pair : IComparable<Pair>
{
public int val;
public int i;
public int j;
public Pair( int val, int i, int j)
{
this .val = val;
this .i = i;
this .j = j;
}
public int CompareTo(Pair other)
{
return this .val - other.val;
}
}
public class GFG
{
static int solve( int [] a, int [] b, int k)
{
Array.Sort(b);
int n = a.Length;
int m = b.Length;
if (n < m)
{
return solve(b, a, k);
}
SortedSet<Pair> heap = new SortedSet<Pair>();
for ( int i = 0; i < n; i++)
{
int curr = a[i];
if (curr < 0)
{
int val = curr * b[0];
heap.Add( new Pair(val, i, 0));
}
else
{
int val = curr * b[m - 1];
heap.Add( new Pair(val, i, m - 1));
}
}
k--;
for ( int i = 0; i < k; i++)
{
Pair pair = heap.Max;
heap.Remove(pair);
int iIndex = pair.i;
int jIndex = pair.j;
int nextJ;
if (a[iIndex] < 0)
{
nextJ = jIndex + 1;
}
else
{
nextJ = jIndex - 1;
}
if (nextJ >= 0 && nextJ < m)
{
int newVal = a[iIndex] * b[nextJ];
heap.Add( new Pair(newVal, iIndex, nextJ));
}
}
return heap.Max.val;
}
static void Main( string [] args)
{
int [] arr = { 1, -2, 3 };
int [] brr = { 3, -4, 0 };
int K = 3;
int val = solve(arr, brr, K);
Console.WriteLine(val);
}
}
|
Javascript
class Pair {
constructor(val, i, j)
{
this .val = val;
this .i = i;
this .j = j;
}
}
function sortFunction(a, b) {
return a[0] - b[0];
}
function solve(a, b, k)
{
b.sort();
let n = k;
let m = k;
if (n < m) {
return solve(b, a, k);
}
let heap = [];
for (let i = 0; i < n; i++) {
let curr = a[i];
if (curr < 0) {
let val = curr * b[0];
heap.push([val, i, 0]);
heap.sort(sortFunction);
}
else
{
let val = curr * b[m - 1];
heap.push([val, i, m - 1]);
heap.sort(sortFunction);
}
}
k--;
for (let i = 0; i < k; i++) {
let pair = heap[heap.length - 1];
heap.pop();
let val = pair[0];
let iIndex = pair[1];
let jIndex = pair[2];
let nextJ = 0;
if (a[iIndex] < 0) {
nextJ = jIndex + 1;
}
else
{
nextJ = jIndex - 1;
}
if (nextJ >= 0 && nextJ < m) {
let newVal = a[iIndex] * b[nextJ];
heap.push([newVal, iIndex, nextJ]);
heap.sort(sortFunction);
}
}
return heap[heap.length - 1][0];
}
let arr = [1, -2, 3];
let brr = [3, -4, 0];
let K = 3;
let val = solve(arr, brr, K);
console.log(val);
|
Time Complexity: O(M*Log(M) + K*Log(N))
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...