according to me, this would be a solution :
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<int> arr = {1 , -1 , 2 , -2 , 3 , -3 , 4 , -4};
int sum = 3;
if(sum % 2){
return 0;
}
int count = 0;
int num = 0;
for(int i = 0 ; i < n ; ++i){
if(abs(arr[i]) == sum/2){
count++;
}
else if(abs(arr[i]) < sum/2){
num++;
}
}
int ans = count*num + (count * (count - 1))/2 ;
cout<<ans<<endl;
return 0;
}First of all, if the sum is odd, then we can never find an integer = sum/2 in the array. Hence, No pair exists.
Here, count*num represents the value(sum / 2) pairing up with all the numbers less than sum/2 which is "num".
And (count*(count - 1))/2 are the pairs of sum/2 with sum/2 i.e. if arr[i] == arr[j] == sum/2.

Join Us

can you pls provide me with the mathematical approach you took to conclude this code
To remove the complexity caused by mod I sorted the array and that is right because we are asked to count unordered pairs so sorting will not change the ans no question became ai-aj+ai+aj=p ==>2*ai=p
Say when the terms are -2 and -4 , then |-2 + -4| = 6 and not -6
hence | -2 - -4| + 6 = 8
which is not same as 2*(-2)
So I feel that this may work when sum is not negative
How the sum of two mod values can be negative?
thats what i said , the values will be positive in that case , whereas in op case it will ignore the signs
According to you, what should be the solution?
To remove the complexity caused by mod I sorted the array and that is right because we are asked to count unorder pairs so sorting will not can that ans no question became ai-aj+ai+aj=p ==>2*ai=p
To remove the complexity caused by mod I sorted the array and that is right because we are asked to count unordered pairs so sorting will not change the ans no question became ai-aj+ai+aj=p ==>2*ai=p