Given two integers A and B where (A ≠ B). The task is to find K such that |A – K| = |B – K|. If no such K exists then print -1.
Input: A = 2, B = 16
|2 – 9| = |16 – 9| = 7
Input: A = 5, B = 2
Approach: It is given that A ≠ B. So let A < B then there are three cases:
- K < A: This gives A – K = B – K which gives A = B which is false.
- K > B: This gives K – A = K – B which is also false.
- A ≤ K ≤ B: This gives K – A = B – K which gives 2 * K = A + B
If A + B is odd, there is thus no solution. If A + B is even then the answer is (A + B) / 2.
Below is the implementation of the above approach:
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.