#include<bits/stdc++.h>
using namespace std;
int main() {
int n,target;
cin>>n;
cin>>target;
vector num;
for(int i=0;i<n;i++){
int val;
cin>>val;
num.push_back(val);
}
sort(num.begin(),num.end());
int closestdiff=INT_MAX;
int closestsum;
for(int i=0;i<=num.size()-3;i++){
int j=i+1,k=num.size()-1;
int sum=0;
sum+=num[i]+num[j]+num[k];
while(j<k){
if(abs(sum-target)<closestdiff){
closestdiff=abs(sum-target);
closestsum=sum;
}
if(sum<target){
sum-=num[j];
j++;
sum+=num[j];
}
else if(sum>target){
sum-=num[k];
k–;
sum+=num[k];
}
else{
cout<<sum<<endl;
}
}
}
cout<<closestsum<<endl;
return 0;
}
Test case 4 ,showing TLE excedeed
@prashantparasharls just exit the program(return 0) after printing sum when sum==target, else program continues in infinite loop
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.