Given a sorted array, we need to find a pair whose sum is closed to the number X in the Array.
For example::
Solution :
You can check each and every pair of numbers and find the sum close to X.
Java code:
Java code:
Solution 2:
- We will maintain two indexes one at beginning (l=0) and one at end (r=n-1)
- iterate until l < r
- Calculate diff as arr[l] + arr[r]-x
- if abs (diff) < minDiff then update the minimum sum and pair.
- If arr[l] + arr[r] is less than X, this means if we want to find sum close to X, do r–
- If arr[l] + arr[r] is greater than 0,this means if we want to find sum close to X , do l++
Java code:
Time complexity: O(NLogN)
Java program to find a pair whose sum is closest to X::
When you run the above program, you will get the below output::
Don't miss the next article! 
Be the first to be notified when a new article or Kubernetes experiment is published.                            
  
Share This
 
 
