What is wrong in this code? test case 2 is giving wrong answer it is giving 2and 4 . it should rather give 4and 6

//pair of roses array challenge
#include<bits/stdc++.h>
#include
#include
using namespace std;

int main() {
int t,n,amount;
int diff=0;
int min_diff=INT_MAX;
int wi,wj;

cin>>t;
while(t!=0){
	cin>>n;
	int price[n];
	for(int i=0;i<n;i++){
		cin>>price[i];
	}
	cin>>amount;
	sort(price,price+n);
	int i=0;
	int j=n-1;
	while(i<j){
			if(price[i]+price[j]==amount){
				diff=abs(price[j]-price[i]);
				if(diff<min_diff){
					min_diff=diff;
					wi=i;
					wj=j;
				}
				i++;
				j--;}


			if(price[i]+price[j]>amount){
                j--;
			}
			if(price[i]+price[j]<amount){
                i++;
			}
		}
		cout<<"Deepak should buy roses whose prices are "<<price[wi]<<" and "<<price[wj]<<"."<<endl;

	t--;


}

return 0;

}

hey @aishnee3sapra_80178610ab2d7d84
This Question is similar to the Array - Target Sum pair. The only difference is to capture that prices of roses which have a minimum difference between them.

Note :- As in this Logic we are traversing our left from 0th to lastIndex and the right from lastIndex to 0 so each time we got pair we will upadate the final ans variables so that each time the difference between them decreases.

1.First sort the given array.
2.Now take two variables one as left and other as right starting from 0th and end index of the sorted array respectively.
3.Now iterate till left<right.
3.1 Calculate the sum of the elements at left and right position
3.1.1 If the sum is equal to the target then print both the elements. //printing target sum pairs
3.1.2 If the sum is less than the target then increase the left by 1
3.1.3 Else decrease the right by 1
4.End loop.Thus, all the pairs has been printed .

Program for finding pair of elements is given below -

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.