Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- Given a sorted array and a number x, find the pair in array whose sum is closest to x
- https://www.geeksforgeeks.org/given-sorted-array-number-x-find-pair-array-whose-sum-closest-x/.
- https://www.tutorialcup.com/array/element-pair-sorted-array-sum-closest-number.htm
- */
- #include <iostream>
- #include <climits>
- #include <cstdlib>
- using namespace std;
- int main()
- {
- int arr[]= {10, 22, 28, 29, 30, 40};
- int N = sizeof(arr)/sizeof(arr[0]);
- int x=54;
- //cin>>x; // the number to which closest sum is to be found
- //left and right pointing at start and end of the sorted array
- int left = 0, right = N-1, sum = 0, closest = INT_MAX , closest_sum;
- int left_sol = left;
- int right_sol = right;
- //sum to store sum , closest to store the minimum difference found and closest_sum to store the actual value closest to x
- while(left < right)
- {
- sum = arr[left] + arr[right];
- if(abs(x-sum) < closest)
- {
- closest = abs(x -sum);
- left_sol = left;
- right_sol = right;
- }
- if(sum > x)
- right--;
- else if(sum <= x)
- left++;
- }
- cout<<"Perechea "<< arr[left_sol]<<" "<<arr[right_sol]<< " ="<<(arr[left_sol] + arr[right_sol])<<endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment