Little C wants to construct an array of n elements that satisfies the following conditions:
- All elements in the array are pairwise distinct
- The greatest common divisor (GCD) of all elements is k
- The sum of the array elements should be as small as possible
Output the minimum possible sum of the array elements that satisfies the conditions.
Input:
n = 3, k = 1Output:
6Explanation: The array [1,2,3] can be constructed, with a sum of 6
Input:
n = 2, k = 2Output:
6Explanation: The array [2,4] can be constructed, with a sum of 6
Input:
n = 4, k = 3Output:
30Explanation: The array [3,6,9,12] can be constructed, with a sum of 30
-
Understanding the requirements:
- We need to find n distinct numbers
- The GCD of these numbers must be k
- The sum of these numbers should be as small as possible
-
Key observation:
- For the GCD to be k, all numbers must be multiples of k
- To minimize the sum, we should choose the smallest multiples of k
- Simply select consecutive multiples of k starting from k
-
Algorithm steps:
- Initialize an empty array result
- Starting from k, add one multiple of k at a time
- Continue until the array length reaches n
- Return the sum of the array elements
def solution(n: int, k: int) -> int:
# Create an array to store the selected numbers
result = []
# Starting from k, find n multiples of k
current = k
while len(result) < n:
result.append(current)
current += k
# Return the sum of array elements
return sum(result)-
result = []: Create an empty array to store the selected numbers -
current = k: Start from k, since k is the smallest possible value -
while len(result) < n:: Loop until n numbers are foundresult.append(current): Add the current number to the arraycurrent += k: Move to the next multiple of k
-
return sum(result): Return the sum of all elements in the array
- Time Complexity: O(n), as we need to find n numbers
- Space Complexity: O(n), as we need to store an array of n numbers
Taking n=4, k=3 as an example:
- Initial current=3, result=[3]
- current=6, result=[3,6]
- current=9, result=[3,6,9]
- current=12, result=[3,6,9,12]
- Return 3+6+9+12=30
- Do not try to find non-multiples of k, as that cannot guarantee the GCD is k
- Do not skip multiples of k, as that would result in a non-minimal sum
- Do not forget the condition that array elements must be pairwise distinct
Related problems:
- GCD-related problems
- Constructive algorithm problems
- Array minimum sum problems