i’m implementing in the same manner as in video but getting TLE can you please suggest changes
TARGET 3 SUM from array
#include <bits/stdc++.h> using namespace std; int main() { int n,i,x,k=0,target; cin>>n; sets; for(i=0;i<n;i++){ cin>>x; s.insert(x); } int a[s.size()]; for(auto itr=s.begin();itr!=s.end();itr++){ a[k++]=*itr; } cin>>target; sort(a,a+s.size()); for(i=0;i<s.size();i++){ int l=i+1; int r=n-1; while(l<r){ if(a[i]+a[l]+a[r]>target){ r–; } else if(a[i]+a[l]+a[r]==target){ cout<<a[i]<<", “<<a[l]<<” and "<<a[r]<<endl; l++;r–; } } } return 0; }
Hey @talhashamim001
#include <bits/stdc++.h>
using namespace std;
int main() {
int n,i,x,k=0,target;
cin>>n;
set<int>s;
for(i=0;i<n;i++){
cin>>x;
s.insert(x);
}
int a[s.size()];
for(auto itr=s.begin();itr!=s.end();itr++){
a[k++]=*itr;
}
cin>>target;
sort(a,a+s.size());
for(i=0;i<s.size();i++){
int l=i+1;
int r=n-1;
while(l<r){
if(a[i]+a[l]+a[r]>target){
r--;
}
else if(a[i]+a[l]+a[r]==target){
cout<<a[i]<<", "<<a[l]<<" and "<<a[r]<<endl;
l++;r--;
}
else l++;//ONLY CORRECTION :added this
}
}
return 0;
}
ohhhh the case whren sum will be smaller …thank you
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.