![]() |
VOOZH | about |
Given two integers X and Y, the task is to find the number of different arrays that can be constructed of size largest possible size that follow the conditions below:
Note: Two arrays will be considered different if at least one element is present in the first array but not in the second one.
Examples:
Input: X = 3, Y = 8
Output: 2
Explanation: 2 arrays of the largest possible size two can be constructed, and the array are {3, 6} and {4, 8}.Input: X = 2, Y = 62
Output: 6
Explanation: 6 arrays can be constructed of the largest possible size five and arrays are {2, 4, 8, 16, 32}, {3, 6, 12, 24, 48}, {2, 4, 8, 16, 48}, {2, 6, 12, 24, 48}, {2, 4, 12, 24, 48} and {2, 4, 8, 24, 48}.
Approach: To solve the problem follow the below idea:
The largest size of the array can be calculated by { 20X, 21*X, 22*X......} till the element is less than or equal to Y.This will be the largest possible size of the array because if we multiply by 1, the element will become the same and if multiple by 3, array size decreases.
We will use Binary search and find in the search range from X to Y, and we will find the highest value of mid such that we can make an array of the largest size if our first element is mid and assign pos1 = mid. But we can also multiply by 3 at most once at any place of 21, 22..., because we if multiply 3 two times, it will reduce array size, instead we can multiply 2 three times which is better 2*2*2<3*3. Using binary search, we can find the highest value of mid such that we can make an array of the largest size if our first element is mid and we can place 3 in any of these positions 21, 22.. and we can place 3 anywhere from a2 to an and assign pos2 = mid. So, Our Final answer will be (pos1-X+1)+(n-1)*(pos2-X+1), where n is the largest possible size of the array..
Below are the steps to implement the approach:
Below is the code for the above approach:
6
Time Complexity: O(Log2N), where N = Y-X
Auxiliary Space: O(1)