Input: X = 5, Y = 14
Output: 5
Explanation:
- When i = 1, subtract i from Y = 14, so new value of Y = 13
- Next, i = 2, add i to X = 5, so new value of X = 7
- When i = 3, subtract i from X = 7, so new value of X = 4
- When i = 4, add i to X, so new value of X = 8
- When i = 5, subtract i from Y = 13, so new value of Y = 8
Thus, X = Y = 8, after 5 operations which is the minimum number of operations to be done.
Input: X = 7, Y = 13
Output: 3
Explanation:
- When i = 1, subtract i from Y = 13, so new value of Y = 12
- Next, i = 2, add i to X = 7, so new value of X =9
- When i = 3, subtract i from Y = 12, so new value of Y = 9
Thus, X = Y = 9, after 3 operations which is the minimum number of operations to be done.
We can say that the number of steps needed does not depend on whether 'i' is even or odd because let's say, when 'i' is odd, subtracting from either X or Y would mean adding 'i' to either Y or X respectively, as what matters is reducing the absolute difference between X and Y.
Let the absolute difference between X and Y be 'd'. Now, we keep on reducing the difference by either adding or subtracting 'i' to the required number each step, which would be minimum when at each step, 'i' contributes to reducing the difference upto a threshold, after which it might exceed 'd'. Thus,
dt = threshold, and the last step be at 'i' = n. So, to determine n:
1 + 2 + .. + n = d
n * (n+1)/2 = d
n2 + n - 2d = 0
n = (-1 + sqrt(1 + 8d))/2
Now, current sum = 1 + 2 + .. + n = n*(n+1)/2
If current sum = d, then minimum number of steps required = n, else
To make 'current sum' = d, in minimum number of steps, we need to keep on adding (n + 1), (n + 2), .. to 'current sum', until the difference between 'current sum' and d becomes even. Let's say at any step m (m > n), the current sum = m*(m + 1)/2 and
h = abs(current sum - d)
where h is a even number.
Then we can reverse the number value at 'h/2' step from +'h/2' to -'h/2', so that our current sum decreases by a value equal to 'h'.