Two approaches better than N^3 exist:
Taking advantage of Sort Function:-(NlogN)
1. Using Binary Search for Third number after selecting 2 numbers; would ensure complexity of N^2LogN
2. Carefully Operating over Numbers that is, Select 1 number and then select other 2 from the middle of Remaining Sum and from there if moving the second pointer to right Sum would Increase and moving the first Pointer to left, sum would Decrease total traversal of N for second and Third indices and N for the first. giving an N^2 complexity.
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
void sort_siei(ll *a,int si,int ei){
if(ei-si<=1){
return;
}
int mi=si+(ei-si)/2;
sort_siei(a,si,mi);
sort_siei(a,mi,ei);
ll *arr=new ll[ei-si];
int i=si;
int j=mi;
int curr_ind=0;
while(i<mi&&j<ei){
if(a[i]<a[j]){
arr[(curr_ind++)]=a[(i++)];
}else{
arr[(curr_ind++)]=a[(j++)];
}
}
while(i<mi){
arr[(curr_ind++)]=a[(i++)];
}
while(j<ei){
arr[(curr_ind++)]=a[(j++)];
}
for(int i=0;i<curr_ind;i++){
arr[i]=a[si+i];
}
delete[] arr;
}
void merge_sort(ll *a,int n){
sort_siei(a,0,n);
}
int main(){
int t;
cin>>t;
while(t--){
int n;
cin>>n;
ll arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
ll x;
cin>>x;
int count=0;
sort(arr,arr+n);
for(int i=0;i<(n-2);i++){
for(int j=i+1;(2*arr[j]+arr[i])<=x;j++){
ll curr_sum=arr[i]+arr[j];
if(binary_search(arr+j+1,arr+n,x-curr_sum)){
count++;
}
}
}
int count2=0;
for(int i=0;i<n-2;i++){
ll rem_sum=x-arr[i];
int k=upper_bound(arr,arr+n,rem_sum/2)-arr;
int j=k-1;
while(j>i&&k<n){
if((arr[j]+arr[k])>rem_sum){
j--;
}
else if((arr[j]+arr[k])<rem_sum){
k++;
}
else{
if(j==(i+1)){
ll cuur_value=arr[k];
while(arr[k]==cuur_value){
k++;
count2++;
}
}
else if((k==n-1)||(arr[j-1]==arr[j])){
ll cuur_value=arr[j];
while(arr[j]==cuur_value){
j--;
count2++;
}
k++;
}
else if(arr[k+1]==arr[k]){
ll cuur_value=arr[k];
while(arr[k]==cuur_value){
k++;
count2++;
}
j--;
}
else{
k++;
j--;
count2++;
}
}
}
}
cout<<"count1"<<count<<"\nCount2"<<count2;
}
}