I know it was easy to solve the problem by using three loops but makes the code bulky and i wanted to know how to minimise the no. of loops ?
i know one such technique where we can use two pointer approach.
We can use two loops!
Outer loop to iterate over the array and inner loop can have two pointer pointing at second element and last element of the array !
and then if the combined value at these points is equal to the (key- value at first pos) then we can count it !!!
But i didn’t get any output …
my code is
#include
#include
using namespace std;
int main() {
int n,key,a[1000];
cin>>n;
for(int i=0 ; i<n ; i++){
cin>>a[i];
}
cin>>key;
sort(a,a+n);
for(int i = 0 ; i < n ;i++){cout<<a[i]<<" ";}
cout<<endl<<key;
int b,c,d,e;
for(int i =0;i<n;i++){
b=i;
for(int j = i+1 ; j<n;j++){
c=j,d=n-1;
e=key-a[b];
if(a[c] + a[d] == e ){
cout<<a[b]<<", "<<a[c]<<" and "<<a[d]<<endl;
}
else if( a[c] + a[d] > e ){
d--;
}
else if( a[c] + a[d] < e ){
c++;
}
}
b++;
}
return 0;
}