Sum of product of all pairs of a Binary Array
Last Updated :
01 Jun, 2021
Given a binary array arr[] of size N, the task is to print the sum of product of all pairs of the given array elements.
Note: The binary array contains only 0 and 1.
Examples:
Input: arr[] = {0, 1, 1, 0, 1}
Output: 3
Explanation: Sum of product of all possible pairs are: {0 × 1 + 0 × 1 + 0 × 0 + 0 × 1 + 1 × 1 + 1 × 0 + 1 × 1 + 1 × 0 + 1 × 1 + 0 × 1}.
Therefore, the required output is 3.
Input: arr[] = {1, 1, 1, 1}
Output: 6
Naive Approach: The simplest approach to solve the problem is to use generate all possible pairs from the array and calculate the sum of their product.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, consider only those pairs in which both the elements are 1. Following are the observations:
If there is a pair (arr[i], arr[j]) where arr[i] × arr[j] = 1, then arr[i] and arr[j] must be 1.
Total number of pairs that satisfy (arr[i] × arr[j] = 1) are:
=>
=> cntOne × (cntOne – 1) / 2
where, cntOne is the count of 1s in the given array
Follow the steps below to solve the problem:
- Initialize the variable cntOne to store the count of 1s from the given array.
- Finally, return the value of cntOne * (cntOne – 1) / 2.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int productSum( int arr[], int N)
{
int cntOne = 0;
for ( int i = 0; i < N; i++)
{
if (arr[i] == 1)
cntOne++;
}
return cntOne * (cntOne - 1) / 2;
}
int main()
{
int arr[] = { 0, 1, 1, 0, 1 };
int n = sizeof (arr) / sizeof (arr[0]);
cout << productSum(arr, n) << endl;
}
|
Java
import java.util.*;
class GFG {
static int productSum( int [] arr)
{
int cntOne = 0 ;
int N = arr.length;
for ( int i = 0 ; i < N; i++) {
if (arr[i] == 1 )
cntOne++;
}
return cntOne * (cntOne - 1 ) / 2 ;
}
public static void main(String[] args)
{
int [] arr = { 0 , 1 , 1 , 0 , 1 };
System.out.println(productSum(arr));
}
}
|
Python3
def productSum(arr):
cntOne = 0
N = len (arr)
for i in range (N):
if (arr[i] = = 1 ):
cntOne + = 1
return cntOne * (cntOne - 1 ) / / 2
arr = [ 0 , 1 , 1 , 0 , 1 ]
print (productSum(arr))
|
C#
using System;
class GFG{
static int productSum( int [] arr)
{
int cntOne = 0;
int N = arr.Length;
for ( int i = 0; i < N; i++)
{
if (arr[i] == 1)
cntOne++;
}
return cntOne * (cntOne - 1) / 2;
}
public static void Main()
{
int [] arr = { 0, 1, 1, 0, 1 };
Console.Write(productSum(arr));
}
}
|
Javascript
<script>
function productSum(arr, N)
{
let cntOne = 0;
for (let i = 0; i < N; i++)
{
if (arr[i] == 1)
cntOne++;
}
return cntOne * (cntOne - 1) / 2;
}
let arr = [ 0, 1, 1, 0, 1 ];
let n = arr.length;
document.write(productSum(arr, n) + "<br>" );
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...