THESE IS THE QUESTION ASKED IN AMAZON AND OYO ROOMS
THE QUESTION IS TO
FIND ALL THE POSSIBLE CASE WHOSE SUM SHOULD BE THE SUM OF FOUR ELEMENTS IN THE ARRAY.
INPUT
8
10 2 3 4 5 9 7 8
23
OUTPUT
3 5 7 8 (3+5+7+8=23)
For Understanding These Question:
https://www.geeksforgeeks.org/find-four-numbers-with-sum-equal-to-given-sum/
For Practicing :
https://practice.geeksforgeeks.org/problems/four-elements/0
PROGRAMME:
#include<bits/stdc++.h>
using namespace std;
void throughnaivesolution(int a[],int n,int X) //time complexity O(n^4)
{
for(int i=0;i<n-3;i++)
{
for(int j=i+1;j<n-2;j++)
{
for(int k=j+1;k<n-1;k++)
{
for(int l=k+1;l<n;l++)
{
if(a[i]+a[j]+a[k]+a[l]==X)
cout<<a[i]<<" "<<a[j]<<" "<<a[k]<<" "<<a[l]<<"\n";
}
}
}
}
}
void throughsorting(int a[],int n,int X) //O(n^3)
{
sort(a,a+n);
for(int i=0;i<n-3;i++) //n
{
for(int j=i+1;j<n-2;j++) //n
{
int k=j+1;
int l=n-1;
while(k<l) //n
{
if(a[i]+a[j]+a[k]+a[l]==X)
{
cout<<a[i]<<" "<<a[j]<<" "<<a[k]<<" "<<a[l]<<"\n";
k++;
l--;
}
else if(a[i]+a[j]+a[k]+a[l]<X)
{
k++;
}
else
l--;
}
}
}
}
main()
{
int t;
cin>>t; // NUMBER OF TEST CASES
while(t--)
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
int X;
cin>>X;
throughnaivesolution(a,n,X);
cout<<"\n\n\n";
throughsorting(a,n,X);
}
}