Target sum triplets-Arrays

//I am using 1 loop while in hint video 2 loops are used ,still i am getting TLE for Arrays Target sum triplets problem.
#include
#include
using namespace std;
int main() {
short n;
int target,i,j,k;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
cin>>target;
i=0;j=n-1;k=i+1;
while(k<=j)
{
if(k==j)
{
i++;
k=i+1;
j=n-1;
}
else if(a[i]+a[j]+a[k]==target)
{
cout<<a[i]<<", ā€œ<<a[k]<<ā€ and "<<a[j]<<endl;
k++;
}
else if(a[i]+a[j]+a[k]>target)
{
j–;
}
}

return 0;

}

@POORVI_SAXENA
hello poorvi,
pls save ur code on -> https://ide.codingblocks.com/ and
share the generated link

@POORVI_SAXENA
there were some implementation mistakes in ur code
https://ide.codingblocks.com/s/209305


a) termination condition should be i<n
b) u should update i even when k> j
c) u havent handled the case when resultant sum is less than target

1 Like