![]() |
VOOZH | about |
Given integers n and m, construct a strictly increasing sequence of m positive integers with sum exactly equal to n such that the GCD of the sequence is maximized. If multiple sequences have the same maximum GCD, return the lexicographically smallest one. If not possible, return -1.
Examples :
Input : n = 24, m = 3
Output : [4, 8, 12]
Explanation : 3, 6, 15 is also a possible sequence having gcd as 3, but 4, 8, 12 has a gcd of 4 which is maximum possible among all.Input : n = 6, m = 4
Output : [-1 ]
Explanation: It is not possible, as the smallest possible GCD sequence would be (1, 2, 3, 4), which gives a sum greater than n. Hence, the answer is -1.
The idea is to form the sequence as
GCD × [1, 2, ..., m]and find the largest possible GCD such that the total sum doesn't exceedn. We then construct the sequence using this GCD, adjusting the last element to match the exact sum. If such a sequence isn't possible, we return-1.
Step by Step Implementations:
m natural numbers: minSum= (m×(m+1))/2, if minSum > n then output will be -1.b = n / minSum. Iterate over all divisors of n which is less than or equal to b to find the largest such divisor r.r × [1, 2, ..., m - 1] as the initial sequence (i.e., [r×1, r×2, r×3, r×4 ,..., r×(m-1)]4 8 12
Time Complexity: O(√n + m), finding all divisors of n takes O(√n) time, and constructing the sequence takes O(m) time.
Space Complexity: O(m)