Balanced K-Factor Decomposition Problem
Description
LeetCode Problem 3669.
You are given two integers n and k.
Split the number n into exactly k positive integers such that the product of these integers is equal to n.
Return any one split in which the maximum difference between any two numbers is minimized. You may return the result in any order.
Example 1:
Input: n = 100, k = 2
Output: [10,10]
Explanation:
The split [10, 10] yields 10 * 10 = 100 and a max-min difference of 0, which is minimal.
Example 2:
Input: n = 44, k = 3
Output: [2,2,11]
Explanation:
- Split [1, 1, 44] yields a difference of 43
- Split [1, 2, 22] yields a difference of 21
- Split [1, 4, 11] yields a difference of 10
- Split [2, 2, 11] yields a difference of 9
Therefore, [2, 2, 11] is the optimal split with the smallest difference 9.
Constraints:
4 <= n <= 10^52 <= k <= 5kis strictly less than the total number of positive divisors ofn.
Solution
Approach: Enumerate Divisors with DFS
Every number in the split divides n, so first list the divisors of n. Then choose the numbers one by one: with x the part of n still to be split, try each divisor y of x as the next number and continue with x / y. The last number is whatever remains. Since k <= 5 and a number up to 10^5 has at most 128 divisors, the search is small.
Along the way keep the smallest and largest number chosen so far. When all k numbers are fixed, the difference is max - min; remember the split with the smallest difference. A branch can be dropped as soon as its current difference is no better than the best found, because adding numbers can only widen it.
Complexity: time roughly O(d^(k-1)) where d is the number of divisors of n (with the pruning it is far less), space O(d + k).
class Solution:
def minDifference(self, n: int, k: int) -> List[int]:
divs = []
i = 1
while i * i <= n:
if n % i == 0:
divs.append(i)
if i * i != n:
divs.append(n // i)
i += 1
divs.sort()
best = [10**9, None]
path = [0] * k
def dfs(i: int, x: int, mi: int, mx: int) -> None:
if i == 0:
d = max(mx, x) - min(mi, x)
if d < best[0]:
best[0] = d
path[0] = x
best[1] = path[:]
return
for y in divs:
if y > x:
break
if x % y == 0 and max(mx, y) - min(mi, y) < best[0]:
path[i] = y
dfs(i - 1, x // y, min(mi, y), max(mx, y))
dfs(k - 1, n, 10**9, 0)
return best[1]