给定大小为N的两个数组A和B。数组A按升序排列,而B按降序排列。这两个数组都是1到2N的数字的子序列。任务是找到两个数组的绝对差之和。
Sum = |A1 – B1| + |A2 – B2| + |A3 – B3| + …. + |AN – BN|
例子:
Input : A[] = {1, 2, 3, 4, 5}, B[] = {10, 9, 8, 7, 6}
Output : 25
Input : A[] = {1, 5, 6, 8, 10, 12}, B[] = {11, 9, 7, 4, 3, 2}
Output : 36
朴素的方法:朴素的方法是运行一个循环并找到绝对差之和。
高效的方法: Proizvolov的恒等式是一个与正整数差之和有关的恒等式。它指出如果我们采用第一个2N个整数并将它们划分为N个数字的两个子集。
以降序排列另一个子集: B 1 > B 2 > B 3 >…。 > B N
然后,总和| A 1 – B 1 | + | A 2 – B 2 | + | A 3 – B 3 | +…。 + | A N – B N |总是等于N 2
下面是上述方法的实现:
C++
// CPP program to implement proizvolov's identity
#include
using namespace std;
// Function to implement proizvolov's identity
int proizvolov(int a[], int b[], int n)
{
// According to proizvolov's identity
return n*n;
}
// Driver code
int main()
{
int a[] = {1, 5, 6, 8, 10}, b[] = {9, 7, 4, 3, 2};
int n = sizeof(a) / sizeof(a[0]);
// Function call
cout << proizvolov(a, b, n);
return 0;
}
Java
// Java program to implement proizvolov's identity
class GFG
{
// Function to implement proizvolov's identity
static int proizvolov(int a [], int b [], int n)
{
// According to proizvolov's identity
return n * n;
}
// Driver code
public static void main (String[] args)
{
int a [] = {1, 5, 6, 8, 10};
int b [] = {9, 7, 4, 3, 2};
int n = a.length;
// Function call
System.out.println(proizvolov(a, b, n));
}
}
// This code is contributed by ihritik
Python3
# Python3 program to implement
# proizvolov's identity
# Function to implement
# proizvolov's identity
def proizvolov(a, b, n):
return n * n
# Driver code
a = [ 1, 5, 6, 8, 10 ]
b = [ 9, 7, 4, 3, 2 ]
n = len(a)
# Function call
print(proizvolov(a, b, n, ))
# This code is contributed by nidhiva
C#
// C# program to implement proizvolov's identity
using System;
class GFG
{
// Function to implement proizvolov's identity
static int proizvolov(int [] a,
int [] b, int n)
{
// According to proizvolov's identity
return n * n;
}
// Driver code
public static void Main ()
{
int [] a = {1, 5, 6, 8, 10};
int [] b = {9, 7, 4, 3, 2};
int n = a.Length;
// Function call
Console.WriteLine(proizvolov(a, b, n));
}
}
// This code is contributed by ihritik
输出:
25