![]() |
VOOZH | about |
Given an array X[] of length N, having all elements less than or equal to M, the task is to print an array let's say Y[] of the same length following the given conditions:
Examples:
Input: N = 4, M = 5, X[] = {2, 2, 2, 2}
Output: Y[] = {2, 4, 4, 4}
Explanation:
- Till index 0: GCD(2) = X[0] = 2.
- Till index 1: GCD(2, 4) = X[1] = 2.
- Till index 2: GCD(2, 4, 4) = X[2] = 2.
- Till index 3: GCD(2, 4, 4, 4) = X[3] = 2.
It can be verified that all the elements of Y[] are also less than or equal to M along with this Y[] is lexographically large as possible. Thus, Y[] follows all the given conditions.
Input: N = 6, M = 7, X[] = {3, 6, 1, 4, 3, 6}
Output: Y[] = {3, 0, 7, 0, 0, 0}
Explanation: It can be verified that the Y[] is lexographically largest possible following all the given conditions.
Approach:
The problem is based on the Number Theory and can be solve using some observations. Let us discuss the observations and approach to solve out this problem.
Here, by reading the problem, First observation that comes to mind is that, If first element of Y[i] will be equal to X[i]. Only then, GCD(Y[0] = X[0]. Therefore, we know that Y[0] must be equal to X[0].
For remaining terms, We need to find the largest number let say num, that is less than or equal to M , such that GCD (num, X[i-1]) = X[i]. So we find the maximum number which is <=M and is a multiple of X[i] in next step of approach.
For doing so, we will iterate from it to back, to find the number which satisfy our condition. If we get the number which satisfy our conditions we assign it to Y[i] and break.
Step-by-step approach:
Below is the implementation of the above approach:
2 4 4 4
Time Complexity: O(N*M)
Auxiliary Space: O(1)