![]() |
VOOZH | about |
Given three integers x, y, and n, the task is to find such a pair of integers a, ?b (1?<=?b?<=?n; 0?<=?a) that the value |x/y - a/b| is as minimal as possible, where |x| represents the absolute value of x.
Examples:
Input: x = 3, y = 7, n = 6
Output: 2/5
Explanation: a=2 and b=5 and b<=6 then 3/7 - 2/5 = 1/35, which is the minimum difference possibleInput: x = 12, y = 37, n = 5
Output: 1/3
Approach: Iterate over the denominator. Let the denominator be i. Then it is required to choose such a numerator d such that |x/y - d/i| is minimal. d = (x*i)/y is a good choice. Also check for d+1. While updating the answer from A/B to d/i, check if x/y - d/i < x/y -A/B or (B*x-y*A) * (i*y) > (i*x-y*d) * (B*y). Follow the steps below to solve the problem:
Below is the implementation of the above approach.
2/5
Time Complexity: O(N)
Auxiliary Space: O(1)