原文:
给定一个由 n 个元素组成的数组 arr[] ,任务是找出给定数组中所有对的绝对差的乘积。
示例:
输入: arr[] = {1,2,3,4} 输出: 10 解释: 积| 2-1 | * | 3-1 | * | 4-1 | * | 3-2 | * | 4-2 | * | 4-3 | = 12 输入: arr[] = {1,8,9,15,16} 输出:
方法:思路是arr【】求所有对的绝对差的乘积。
以下是上述方法的实现:
c
// c program for the above approach
#include
using namespace std;
// function to return the product of
// abs diff of all pairs (x, y)
int getproduct(int a[], int n)
{
// to store product
int p = 1;
// iterate all possible pairs
for (int i = 0; i < n; i ) {
for (int j = i 1; j < n; j ) {
// find the product
p *= abs(a[i] - a[j]);
}
}
// return product
return p;
}
// driver code
int main()
{
// given array arr[]
int arr[] = { 1, 2, 3, 4 };
int n = sizeof(arr) / sizeof(arr[0]);
// function call
cout << getproduct(arr, n);
return 0;
}
java 语言(一种计算机语言,尤用于创建网站)
// java program for the above approach
import java.util.*;
class gfg{
// function to return the product of
// abs diff of all pairs (x, y)
static int getproduct(int a[], int n)
{
// to store product
int p = 1;
// iterate all possible pairs
for(int i = 0; i < n; i )
{
for(int j = i 1; j < n; j )
{
// find the product
p *= math.abs(a[i] - a[j]);
}
}
// return product
return p;
}
// driver code
public static void main(string[] args)
{
// given array arr[]
int arr[] = { 1, 2, 3, 4 };
int n = arr.length;
// function call
system.out.println(getproduct(arr, n));
}
}
// this code is contributed by ritik bansal
python 3
# python3 program for
# the above approach
# function to return the product of
# abs diff of all pairs (x, y)
def getproduct(a, n):
# to store product
p = 1
# iterate all possible pairs
for i in range (n):
for j in range (i 1, n):
# find the product
p *= abs(a[i] - a[j])
# return product
return p
# driver code
if __name__ == "__main__":
# given array arr[]
arr = [1, 2, 3, 4]
n = len(arr)
# function call
print (getproduct(arr, n))
# this code is contributed by chitranayal
c
// c# program for the above approach
using system;
class gfg{
// function to return the product of
// abs diff of all pairs (x, y)
static int getproduct(int []a, int n)
{
// to store product
int p = 1;
// iterate all possible pairs
for(int i = 0; i < n; i )
{
for(int j = i 1; j < n; j )
{
// find the product
p *= math.abs(a[i] - a[j]);
}
}
// return product
return p;
}
// driver code
public static void main(string[] args)
{
// given array arr[]
int []arr = { 1, 2, 3, 4 };
int n = arr.length;
// function call
console.write(getproduct(arr, n));
}
}
// this code is contributed by rutvik_56
java 描述语言
output:
12
时间复杂度:o(n2) 辅助空间: o(1)
麻将胡了pg电子网站的版权属于:月萌api www.moonapi.com,转载请注明出处