# Kth largest pairwise product possible from given two Arrays

• Last Updated : 11 Feb, 2022

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 ``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++) {` `      ``// take product``      ``int` `prod = a[i] * b[j];``      ``ans.push_back(prod);``    ``}``  ``}` `  ``// Sort array in descending order``  ``sort(ans.begin(), ans.end(), greater<``int``>());` `  ``// Finally return (k - 1)th index``  ``// as indexing begin from 0.``  ``return` `ans[k - 1];``}` `// Driver code``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``);``  ` `  ``// Function Call``  ``int` `val = solve(arr, n, brr, m, K);` `  ``cout << val;` `  ``return` `0;``}` `// This code is contributed by hrithikgarg03188`

## Java

 `// Java code for the above approach``import` `java.util.Collections;``import` `java.util.LinkedList;``import` `java.util.List;` `class` `GFG {` `  ``static` `int` `solve(``int``[] a, ``int``[] b, ``int` `k) {``    ``List 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++) {` `        ``// take product``        ``int` `prod = a[i] * b[j];``        ``ans.add(prod);``      ``}``    ``}` `    ``// Sort array in descending order``    ``Collections.sort(ans, (x, y) -> y - x);` `    ``// Finally return (k - 1)th index``    ``// as indexing begins from 0.``    ``return` `(ans.get(k - ``1``));``  ``}` `  ``// Driver Code``  ``public` `static` `void` `main(String[] args)``  ``{` `    ``int``[] arr = { ``1``, -``2``, ``3` `};``    ``int``[] brr = { ``3``, -``4``, ``0` `};``    ``int` `K = ``3``;` `    ``// Function Call``    ``int` `val = solve(arr, brr, K);` `    ``System.out.println(val);` `  ``}``}` `// This code is contributed by 29AjayKumar`

## Python3

 `# Python program for above approach``def` `solve(a, b, k):``    ``ans ``=` `[]``    ``n ``=` `len``(a)``    ``m ``=` `len``(b)` `    ``for` `i ``in` `range``(n):``        ``for` `j ``in` `range``(m):` `            ``# take product``            ``prod ``=` `a[i]``*``b[j]``            ``ans.append(prod)` `    ``# Sort array in descending order``    ``ans.sort(reverse ``=` `True``)` `    ``# Finally return (k-1)th index``    ``# as indexing begins from 0.``    ``return` `(ans[k``-``1``])`  `# Driver Code``arr ``=` `[``1``, ``-``2``, ``3``]``brr ``=` `[``3``, ``-``4``, ``0``]``K ``=` `3` `# Function Call``val ``=` `solve(arr, brr, K)` `print``(val)`

## C#

 `// C# code for the above approach``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++) {` `        ``// take product``        ``int` `prod = a[i] * b[j];``        ``ans.Add(prod);``      ``}``    ``}` `    ``// Sort array in descending order``    ``ans.Sort((x, y) => y - x);` `    ``// Finally return (k - 1)th index``    ``// as indexing begins from 0.``    ``return` `(ans[k - 1]);``  ``}` `  ``// Driver Code``  ``public` `static` `void` `Main(String[] args)``  ``{` `    ``int``[] arr = { 1, -2, 3 };``    ``int``[] brr = { 3, -4, 0 };``    ``int` `K = 3;` `    ``// Function Call``    ``int` `val = solve(arr, brr, K);` `    ``Console.WriteLine(val);` `  ``}``}` `// This code is contributed by 29AjayKumar`

## Javascript

 ``
Output:
`3`

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.

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.

## Python3

 `# Python program for above approach``from` `heap ``import` `heappush as push, heappop as pop`  `def` `solve(a, b, k):` `    ``# Sorting array b in ascending order``    ``b.sort()``    ``n, m ``=` `len``(a), ``len``(b)` `    ``# Checking if size(a) > size(b)` `    ``if` `(n < m):` `        ``# Otherwise swap the arrays` `        ``return` `solve(b, a, k)` `    ``heap ``=` `[]` `    ``# Traverse all elements in array a``    ``for` `i ``in` `range``(n):` `        ``curr ``=` `a[i]` `        ``# curr element is negative``        ``if` `(curr < ``0``):` `            ``# Product with smallest value``            ``val ``=` `curr ``*` `b[``0``]` `            ``# Pushing negative val due to max heap``            ``# and i as well jth index``            ``push(heap, (``-``val, i, ``0``))` `        ``else``:` `            ``# Product with largest value``            ``val ``=` `curr ``*` `b[``-``1``]` `            ``# Pushing negative val due to max heap``            ``# and i as well jth index``            ``push(heap, (``-``val, i, m``-``1``))` `    ``# Subtract 1 due to zero indexing``    ``k ``=` `k``-``1` `    ``# Remove k-1 largest items from heap``    ``for` `_ ``in` `range``(k):` `        ``val, i, j ``=` `pop(heap)``        ``val ``=` `-``val` `        ``# if a[i] is negative, increment ith index` `        ``if` `(a[i] < ``0``):``            ``next_j ``=` `j ``+` `1` `        ``# if a[i] is positive, decrement jth index``        ``else``:``            ``next_j ``=` `j``-``1` `        ``# if index is valid``        ``if` `(``0` `<``=` `next_j < m):` `            ``new_val ``=` `a[i] ``*` `b[next_j]` `            ``# Pushing new_val in the heap``            ``push(heap, (``-``new_val, i, next_j))` `    ``# Finally return first val in the heap``    ``return` `-``(heap[``0``][``0``])`  `# Driver Code``arr ``=` `[``1``, ``-``2``, ``3``]``brr ``=` `[``3``, ``-``4``, ``0``]``K ``=` `3` `# Function Call``val ``=` `solve(arr, brr, K)` `# Print the result``print``(val)`
Output:
`3`

Time Complexity: O(M*Log(M) + K*Log(N))
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up