给定两个数组A []和B [] ,任务是选择两个元素X和Y ,使得X属于A []且Y属于B [],并且(X + Y)不能存在于任何一个大批。
例子:
Input: A[] = {3, 2, 2}, B[] = {1, 5, 7, 7, 9}
Output: 3 9
3 + 9 = 12 and 12 is not present in
any of the given arrays.
Input: A[] = {1, 3, 5, 7}, B[] = {7, 5, 3, 1}
Output: 7 7
方法:选择X作为从A []和Y从B []的最大元素作为最大元素。现在,很明显(X + Y)将大于两个数组的最大值,即它不会出现在所有数组中。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to find the numbers from
// the given arrays such that their
// sum is not present in any
// of the given array
void findNum(int a[], int n, int b[], int m)
{
// Find the maximum element
// from both the arrays
int x = *max_element(a, a + n);
int y = *max_element(b, b + m);
cout << x << " " << y;
}
// Driver code
int main()
{
int a[] = { 3, 2, 2 };
int n = sizeof(a) / sizeof(int);
int b[] = { 1, 5, 7, 7, 9 };
int m = sizeof(b) / sizeof(int);
findNum(a, n, b, m);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// find maximum element in an array
static int max_element(int a[], int n)
{
int m = Integer.MIN_VALUE;
for(int i = 0; i < n; i++)
m = Math.max(m, a[i]);
return m;
}
// Function to find the numbers from
// the given arrays such that their
// sum is not present in any
// of the given array
static void findNum(int a[], int n,
int b[], int m)
{
// Find the maximum element
// from both the arrays
int x = max_element(a, n);
int y = max_element(b, m);
System.out.print(x + " " + y);
}
// Driver code
public static void main(String args[])
{
int a[] = { 3, 2, 2 };
int n = a.length;
int b[] = { 1, 5, 7, 7, 9 };
int m = b.length;
findNum(a, n, b, m);
}
}
// This code is contributed by Arnub Kundu
Python3
# Python3 implementation of the approach
# Function to find the numbers from
# the given arrays such that their
# sum is not present in any
# of the given array
def findNum(a, n, b, m) :
# Find the maximum element
# from both the arrays
x = max(a);
y = max(b);
print(x, y);
# Driver code
if __name__ == "__main__" :
a = [ 3, 2, 2 ];
n = len(a);
b = [ 1, 5, 7, 7, 9 ];
m = len(b);
findNum(a, n, b, m);
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// find maximum element in an array
static int max_element(int []a, int n)
{
int m = int.MinValue;
for(int i = 0; i < n; i++)
m = Math.Max(m, a[i]);
return m;
}
// Function to find the numbers from
// the given arrays such that their
// sum is not present in any
// of the given array
static void findNum(int []a, int n,
int []b, int m)
{
// Find the maximum element
// from both the arrays
int x = max_element(a, n);
int y = max_element(b, m);
Console.Write(x + " " + y);
}
// Driver code
public static void Main()
{
int []a = { 3, 2, 2 };
int n = a.Length;
int []b = { 1, 5, 7, 7, 9 };
int m = b.Length;
findNum(a, n, b, m);
}
}
// This code is contributed by kanugargng
Javascript
输出:
3 9
时间复杂度: O(n)