Minimize Array Sum Using Divisible Replacements Problem
Description
LeetCode Problem 3927.
You are given an integer array nums.
You can perform the following operation any number of times:
- Choose two indices
aandbsuch thatnums[a] % nums[b] == 0. - Replace
nums[a]withnums[b].
Return the minimum possible sum of the array after performing any number of operations.
Example 1:
Input: nums = [3,6,2]
Output: 7
Explanation:
- Choose a = 1, b = 2, where nums[a] = 6 and nums[b] = 2. Since 6 % 2 == 0, replace nums[1] with nums[2].
- The array becomes [3, 2, 2].
- No further operation reduces the sum. Thus, the final sum is 3 + 2 + 2 = 7.
Example 2:
Input: nums = [4,2,8,3]
Output: 9
Explanation:
- Choose a = 0, b = 1, where nums[a] = 4 and nums[b] = 2. Since 4 % 2 == 0, replace nums[0] with nums[1].
- Choose a = 2, b = 1, where nums[a] = 8 and nums[b] = 2. Since 8 % 2 == 0, replace nums[2] with nums[1].
- The array becomes [2, 2, 2, 3].
- No further operation reduces the sum. Thus, the final sum is 2 + 2 + 2 + 3 = 9.
Example 3:
Input: nums = [7,5,9]
Output: 21
Explanation:
- There is no pair (a, b) such that nums[a] % nums[b] == 0.
- Hence, no operation can be performed. The sum remains 7 + 5 + 9 = 21.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Smallest Divisor Present (Sieve)
A number v can be replaced by any value d in the array with d | v, and by chaining replacements nothing smaller than the smallest such divisor can be reached (a divisor of d that is also in the array already divides v). So every element becomes the smallest value in nums that divides it.
Let m be the maximum value. Mark which values appear, then go through d = 1..m in increasing order and, for each marked d, assign best[y] = d to every multiple y of d that has no best yet. The answer is the sum of best[x] over all x in nums; use a 64-bit sum.
Complexity: O(n + m log m) time (a harmonic sum over the multiples) and O(m) extra space.
class Solution:
def minArraySum(self, nums: List[int]) -> int:
m = max(nums)
present = [False] * (m + 1)
for x in nums:
present[x] = True
best = [0] * (m + 1)
for d in range(1, m + 1):
if present[d]:
for y in range(d, m + 1, d):
if best[y] == 0:
best[y] = d
return sum(best[x] for x in nums)