Sum of all ordered pair-products from a given array
Last Updated :
07 May, 2021
Given an array arr[] of size N, the task is to find the sum of all products of ordered pairs that can be generated from the given array elements.
Examples:
Input: arr[] ={1, 2, 3}
Output: 36
Explanation:All possible pairs are {(1, 1), {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}}. Therefore, the sum of product of all pairs is 36.
Input : arr[]={3, 4, 1, 2, 5}
Output: 225
Naive Approach: The simplest approach is to iterate through all possible pairs from the given array calculate the sum of product of all pair-products.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The above approach can be optimized based on the following observations:
arr[]={a1, a2, a3, a4 ….., an-1, an}
Now, sum of product of all possible pairs is =
{
(a1 * a1) + (a1 * a2) + (a1 * a3) + …..+ (a1 * an-1) + (a1, an) +
(a2 * a1) + (a2 * a2) + (a2 * a3) + ….. + (a2 * an-1) + (a2 * an) +
(a3 * a1) + (a3 * a2) + (a3 * a3) + ….. + (a3 * an-1) + (a3, an) +
…………………………………………………………………………..
(an, * a1) + (an * a2), +(an * a3) + ….. + (an * an-1) + (an, an)
}
={
(a1 + a2+ a3 + …..+ an-1 + an ) * (a1 + a2+ a3 + …..+ an-1 + an )
}
=(a1 + a2+ a3 + …..+ an-1 + an )2
Follow the steps below to solve the problem:
- Initialize the variable, res=0 to store the sum of array elements
- Traverse the array, arr[] and add each element of the array to res.
- Finally, print the square of the res as the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int sumOfProd( int arr[], int N)
{
int sum = 0;
for ( int i = 0; i < N; i++) {
sum += arr[i];
}
return sum * sum;
}
int main()
{
int arr[] = { 2, 3, 1, 5, 4 };
int N = sizeof (arr) / sizeof (arr[0]);
cout << sumOfProd(arr, N);
return 0;
}
|
Java
import java.util.*;
class GFG{
static int sumOfProd( int arr[], int N)
{
int sum = 0 ;
for ( int i = 0 ; i < N; i++)
{
sum += arr[i];
}
return sum * sum;
}
public static void main(String[] args)
{
int arr[] = { 2 , 3 , 1 , 5 , 4 };
int N = arr.length;
System.out.print(sumOfProd(arr, N));
}
}
|
Python3
def sumOfProd(arr, N):
sum = 0
for i in range (N):
sum + = arr[i]
return sum * sum
if __name__ = = '__main__' :
arr = [ 2 , 3 , 1 , 5 , 4 ]
N = len (arr)
print (sumOfProd(arr, N))
|
C#
using System;
class GFG{
static int sumOfProd( int [] arr, int N)
{
int sum = 0;
for ( int i = 0; i < N; i++)
{
sum += arr[i];
}
return sum * sum;
}
static void Main()
{
int [] arr = { 2, 3, 1, 5, 4 };
int N = arr.Length;
Console.WriteLine(sumOfProd(arr, N));
}
}
|
Javascript
<script>
function sumOfProd(arr, N)
{
let sum = 0;
for (let i = 0; i < N; i++)
{
sum += arr[i];
}
return sum * sum;
}
let arr = [ 2, 3, 1, 5, 4 ];
let N = arr.length;
document.write(sumOfProd(arr, N));
</script>
|
Output:
225
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...