one of a test case is failed but I get the same output when I provide same custom input
Target Sum of pairs in an array
hi ritika can you please share your code
#include
#include
using namespace std;
int main()
{
int n;
cin>>n;
int arr[100];
for(int i=0;i<n;i++)
cin>>arr[i];
sort(arr,arr+n);
int target;
cin>>target;
int left, right;
int sum=0;
left =arr[0];
right=arr[n-1];
while(left<right){
sum= left+right;
if(sum==target){
cout<<left<<" and "<<right;
cout<<endl;
}
if(sum<target){
left++;
}
else
right–;
}
return 0;
}
you have initialized left as arr[0] and right as arr[n-1] and incrementing or decrementing it. but incrementing and decrementing would not solve the problem as we are supposed to increment or decrement the indexes according to the requirement (bcoz we have to check for the 2 numbers in array which would have sum equal to target)
instead initialize left=0 and right =n-1
#include<bits/stdc++.h>
using namespace std;
int main() {
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
sort(a,a+n);
int t;
cin>>t;
map<int,int> m;
map<int,int> :: iterator itr;
for(int i=0;i<n;i++){
itr = m.find(a[i]);
if(itr==m.end()){
m.insert(pair<int,int>((t-a[i]),i));
}
else{
if(a[i]>(t-a[i])){
cout<<(t-a[i])<<" and "<<a[i]<<endl;
}
else{
cout<<a[i]<<" and "<<(t-a[i])<<endl;
}
m.erase(a[i]);
}
}
}
Can someone pls tell me the mistake in my logic…