# Count of elements whose absolute difference with the sum of all the other elements is greater than k in C++

We are given an array of integers. The goal is to count numbers such that the absolute difference between the sum of all elements and that element is greater than variable k.

We will do this by getting the sum of elements of the array. Now for each element arr[i], check if −

sum-2(arr[i])>k, as sum already includes arr[i] so subtract it twice. If true increment count.

Let’s understand with examples.

Input − arr[]= { 1,2,3,0,3,2,0,1 }, k=10

Output − Count of elements: 2

Explanation − Sum of elements is 12

12-1-1=10, 12-2-2=8, 12-3-3=6, 12-0-0=12.

Only 12 > 10, so for 2 elements (0s) the condition is true.

Input − arr[]= { 1,1,1,1,1 } k=10

Output − Count of elements: 0

Explanation − Sum of elements is 5

For each 1 5-1-1=3 <10 .

## Approach used in the below program is as follows

• We take an integer array arr[] initialized with random numbers.

• Function numberCount(int arr[], int n, int k) takes array and its length as input and returns count of elements whose absolute difference with the sum of all the other elements is greater than k

• Take the initial count as 0.

• Calculate sum of all elements of array as sum.

• Now trvaser whole array from i=0 to i<n.

• FOr each element arr[i], if sum-arr[i]-arr[i]>k, increment count.

• Return count at the end of loop as final result.

## Example

Live Demo

#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int numberCount(int arr[],int n, int k){
int count=0;
int sum=0;
int i;
for(i=0;i<n;i++)
{ sum+=arr[i]; }
for(int i=0;i<n;i++){
if( abs(sum-arr[i]-arr[i]) > k ){
count++;
}
}
return count;
}
int main(){
int Arr[]={ 1,2,3,4 };
int len=sizeof(Arr)/sizeof(Arr[0]);
int K=5;
cout<<endl<<"Count of elements: "<<numberCount(Arr,len,K);
return 0;
}

## Output

If we run the above code it will generate the following output −

Count of elements: 2