给定两个数组可能的第 K 个最大成对积
给定两个包含整数的数组arr[]和brr[] 。任务是找到一对(arr[i], brr[j])的第K个最大乘积。
例子:
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.
天真的方法:为数组arr[]中的每个元素与数组brr[]中的每个元素生成所有可能的产品组合。然后对结果数组进行排序并返回结果数组的第 K 个元素。
C++
#include
using namespace std;
int solve(int a[ ], int n, int b[ ], int m, int k) {
vector 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());
// 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 ans = new List();
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
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)
3
时间复杂度: O(N*M + (N+M) * Log(N+M))
辅助空间: O(N+M)
高效方法:这个问题可以通过使用贪心方法和堆来解决。请按照以下步骤解决给定的问题。
- 对brr[]数组进行排序。
- 在数组arr[]中保留更大的数组。
- 创建一个最大堆来存储元素及其各自的索引。
- 遍历数组arr[]中的每个元素。该元素可以是正的或负的。
- 正:将arr[]中的当前元素与排序数组brr[]的最大元素相乘。确保获得最大元素。
- 负数:在这种情况下,乘以最小值,即与数组brr[]中的第一个元素相乘。这是由于否定的性质,因为可以通过乘以最小的值来获得更大的值。
- 将三个值插入堆中,这样: ( product, i, j )其中i & j是数组arr[]和brr[]的索引。
- 现在运行一个for 循环 K 次并从堆中弹出元素。
- 现在检查arr[i]的值是正还是负
- 正:所以next_j = ( current_j – 1)因为使用了最大堆,所有更高的索引可能已经从堆中弹出。
- 负数: next_j = (current_j +1)因为所有产生较大元素的较小值可能已经从堆中弹出。
- 最后,返回答案
注意:最大堆是在min-heap的帮助下实现的,在Python中将值的符号取反,同时将它们插入堆中。
下面是上述方法的实现。
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)
3
时间复杂度: O(M*Log(M) + K*Log(N))
辅助空间: O(N)