madalinaradu

P26 - pereche de suma apropiata

Apr 29th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.17 KB | None | 0 0
  1. /**
  2. Given a sorted array and a number x, find the pair in array whose sum is closest to x
  3. https://www.geeksforgeeks.org/given-sorted-array-number-x-find-pair-array-whose-sum-closest-x/.
  4. https://www.tutorialcup.com/array/element-pair-sorted-array-sum-closest-number.htm
  5. */
  6. #include <iostream>
  7. #include <climits>
  8. #include <cstdlib>
  9. using namespace std;
  10.  
  11. int main()
  12. {
  13.     int arr[]= {10, 22, 28, 29, 30, 40};
  14.     int N = sizeof(arr)/sizeof(arr[0]);
  15.  
  16.     int x=54;
  17.     //cin>>x; // the number to which closest sum is to be found
  18.  
  19.     //left and right pointing at start and end of the sorted array
  20.     int left = 0, right = N-1, sum = 0, closest = INT_MAX , closest_sum;
  21.     int left_sol = left;
  22.     int right_sol = right;
  23.  
  24.  
  25.     //sum to store sum , closest to store the minimum difference found and closest_sum to store the actual value closest to x
  26.     while(left < right)
  27.     {
  28.         sum = arr[left] + arr[right];
  29.         if(abs(x-sum) < closest)
  30.         {
  31.             closest = abs(x -sum);
  32.  
  33.             left_sol = left;
  34.             right_sol = right;
  35.         }
  36.         if(sum > x)
  37.             right--;
  38.         else if(sum <= x)
  39.             left++;
  40.     }
  41.     cout<<"Perechea "<< arr[left_sol]<<" "<<arr[right_sol]<< " ="<<(arr[left_sol] + arr[right_sol])<<endl;
  42. }
Advertisement
Add Comment
Please, Sign In to add comment