4005. Minimum Operations to Make Array Equal III π
Description
You are given an integer array nums.
In one operation, you may choose any element nums[i] and perform one of the following:
- Multiply
nums[i]by an integerk, wherek >= 2. - Divide
nums[i]by an integerk, where2 <= k < nums[i], provided thatnums[i]is divisible byk.
Return the minimum number of operations required to make all elements of nums equal.
Example 1:
Input: nums = [6,12,8]
Output: 3
Explanation:
We can perform following operates to make all numbers to 6:
- Divide
nums[1] = 12by 2 to get 6. - Divide
nums[2] = 8by 4 to get 2. - Multiply
nums[2] = 2by 3 to get 6.
Example 2:
Input: nums = [5,15,20]
Output: 2
Explanation:
We can perform following operates to make all numbers to 5:
- Divide
nums[1] = 15by 3 to get 5. - Divide
nums[2] = 20by 4 to get 5.
Example 3:
Input: nums = [7,7,7]
Output: 0
Explanation:
All elements are already equal, so no operations are needed.
Constraints:
1 <= nums.length <= 1051 <= nums[i] <= 10βββββββ9
Solutions
Solution 1
Thinking
With \(n\) up to \(10^5\) and values up to \(10^9\), we cannot simulate multiplications and divisions on every pair, nor test every reachable integer as a common target.
A single multiply or exact divide jumps a number to any multiple or proper divisor, so the cost of meeting at one target is governed by common factors and the extra factors each value must add or stripβnot by the number of intermediate integers.
We therefore compress each number by its factorization and accumulate the minimum operations over a candidate set far smaller than \(10^9\).
1 | |
1 | |
1 | |
1 | |