The Wayback Machine - https://web.archive.org/web/20211231125842/https://www.geeksforgeeks.org/kth-largest-pairwise-product-possible-from-given-two-arrays/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Kth largest pairwise product possible from given two Arrays

  • Last Updated : 29 Dec, 2021

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: 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

Input: arr[] = {1, -2, 3}, brr[] = {3, -4, 0}, K = 3
Output: 3
Explaination: 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
Explaination: 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.

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 begans 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)
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.
  • 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.

Python3




# Python program for above approach
from heapq 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 = []
  
    # Tarverse 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
Recommended Articles
Page :

Start Your Coding Journey Now!