Product of absolute difference of every pair in given Array
Last Updated :
30 Jan, 2023
Given an array arr[] of N elements, the task is to find the product of absolute differences of all pairs in the given array.
Examples:
Input: arr[] = {1, 2, 3, 4}
Output: 12
Explanation:
Product of |2-1| * |3-1| * |4-1| * |3-2| * |4-2| * |4-3| = 12
Input: arr[] = {1, 8, 9, 15, 16}
Output: 27659520
Approach: The idea is to generate every possible pairs of the given array arr[] and find the product of the absolute difference of all the pairs.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int getProduct( int a[], int n)
{
int p = 1;
for ( int i = 0; i < n; i++) {
for ( int j = i + 1; j < n; j++) {
p *= abs (a[i] - a[j]);
}
}
return p;
}
int main()
{
int arr[] = { 1, 2, 3, 4 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << getProduct(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int getProduct( int a[], int n)
{
int p = 1 ;
for ( int i = 0 ; i < n; i++)
{
for ( int j = i + 1 ; j < n; j++)
{
p *= Math.abs(a[i] - a[j]);
}
}
return p;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 3 , 4 };
int N = arr.length;
System.out.println(getProduct(arr, N));
}
}
|
Python3
def getProduct(a, n):
p = 1
for i in range (n):
for j in range (i + 1 , n):
p * = abs (a[i] - a[j])
return p
if __name__ = = "__main__" :
arr = [ 1 , 2 , 3 , 4 ]
N = len (arr)
print (getProduct(arr, N))
|
C#
using System;
class GFG{
static int getProduct( int []a, int n)
{
int p = 1;
for ( int i = 0; i < n; i++)
{
for ( int j = i + 1; j < n; j++)
{
p *= Math.Abs(a[i] - a[j]);
}
}
return p;
}
public static void Main( string [] args)
{
int []arr = { 1, 2, 3, 4 };
int N = arr.Length;
Console.Write(getProduct(arr, N));
}
}
|
Javascript
<script>
function getProduct( a, n)
{
var p = 1;
for ( var i = 0; i < n; i++) {
for ( var j = i + 1; j < n; j++) {
p *= Math.abs(a[i] - a[j]);
}
}
return p;
}
var arr = [ 1, 2, 3, 4 ];
var N = arr.length;
document.write( getProduct(arr, N));
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...