Program to find out the k-th largest product of elements of two arrays in Python



Suppose we are given two lists, p and q that contain some integer numbers. We have to multiply all the values of these lists and have to find out the k-th largest value from the multiplication results.

So, if the input is like p = [2, 5], q = [6, 8], k = 2, then the output will be 16.

The multiplication results are: 2 * 6 = 12, 2 * 8 = 16, 5 * 6 = 30, 5 * 8 = 40. The 2nd largest element at is (index starts from 0) is 16.

To solve this, we will follow these steps −

  • sort the list p
  • sort the list q
  • k := k + 1
  • heap := a new heap in a list representation
  • for each elem in q, do
    • if elem >= 0, then
      • for i in range (size of p - 1 ) to -1, decrease by 1, do
        • cd := elem * p[i]
        • if heap is not empty and size of heap is same as k and cd <= heap[0], then
          • come out from the loop
        • insert the value cd into heap
        • if length of (heap) > k, then
          • delete the smallest item from heap
    • otherwise,
      • for i in range 0 to size of p, do
        • cd := elem * p[i]
        • if heap is not empty and size of heap is same as k and cd <= heap[0], then
          • come out from the loop
        • insert cd into the heap
        • if length of (heap) > k is non-zero, then
          • delete the smallest item from the loop
  • return heap[0]

Example

Let us see the following implementation to get better understanding −

from heapq import heappush, heappop
def solve(p, q, k):
p = sorted(p)
q = sorted(q)
k += 1
heap = []
for elem in q:
if elem >= 0:
for i in range((len(p) - 1), -1, -1):
cd = elem * p[i]
if heap and len(heap) == k and cd <= heap[0]:
break
heappush(heap, cd)
if len(heap) > k:
heappop(heap)
else:
for i in range(len(p)):
cd = elem * p[i]
if heap and len(heap) == k and cd <= heap[0]:
break
heappush(heap, cd)
if len(heap) > k:
heappop(heap)
return heap[0]
print(solve([2, 5], [6, 8], 2))

Input

[2, 5], [6, 8], 2

Output

16

Advertisements