https://ide.codingblocks.com/s/51301
actually i did this problem with the help of loop but i tried to apply new approach first i sort my array and after that i will search for pair but my code does not run properly kindly debug
Array target sum pair
i tell me how to implement the better approach
Hey Neeraj, your approach is correct, you have made just a small mistake in if check if (arr[start]+arr[last]==target) after getting a desirable pair you should increment start and decrement last as well. So, update your if check like this
if (arr[start]+arr[last]==target)
{ j=arr[start];
k=arr[last];
cout<<j<<k<<endl;
start++;
last--;
}
- in this problem first you will get no. of elements of array, then all the array elements and after that you will get the target, So, take your inputs in this manner only.
- your output should exactly match the output format, so update your printing statement like this
cout<<j<<" and "<<k<<endl;
@sanjeetboora what if i try to solve this approach to solve array triplet target sum how should start it
Hey Neeraj, you can try but i don’t think this approach would work for triplet because by this approach you can target only 2 elements at a time.
@sanjeetboora no if i divide my array in two part in first part i store one pair among three and rest i search for two pair in rest of the array does it work
Hey, I am unable to get it… you mean you will pick one element and then you will search for other 2 elements in the array so that this triplet will result in the target sum ?? if you meant this then yes it will work and If you are trying to convey some other approach to this problem then do reply to this thread and elaborate a little bit more .
ok i will code for this approach and I will tag you if i need help in debug
Yes Sure 