Minimize the Maximum of Two Arrays Problem
#2513
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2513.
We have two arrays arr1 and arr2 which are initially empty. You need to add positive integers to them such that they satisfy all the following conditions:
arr1containsuniqueCnt1distinct positive integers, each of which is not divisible bydivisor1.arr2containsuniqueCnt2distinct positive integers, each of which is not divisible bydivisor2.- No integer is present in both
arr1andarr2.
Given divisor1, divisor2, uniqueCnt1, and uniqueCnt2, return the minimum possible maximum integer that can be present in either array.
Example 1:
Input: divisor1 = 2, divisor2 = 7, uniqueCnt1 = 1, uniqueCnt2 = 3
Output: 4
Explanation:
We can distribute the first 4 natural numbers into arr1 and arr2.
arr1 = [1] and arr2 = [2,3,4].
We can see that both arrays satisfy all the conditions.
Since the maximum value is 4, we return it.
Example 2:
Input: divisor1 = 3, divisor2 = 5, uniqueCnt1 = 2, uniqueCnt2 = 1
Output: 3
Explanation:
Here arr1 = [1,2], and arr2 = [3] satisfy all conditions.
Since the maximum value is 3, we return it.
Example 3:
Input: divisor1 = 2, divisor2 = 4, uniqueCnt1 = 8, uniqueCnt2 = 2
Output: 15
Explanation:
Here, the final possible arrays can be arr1 = [1,3,5,7,9,11,13,15], and arr2 = [2,6].
It can be shown that it is not possible to obtain a lower maximum satisfying all conditions.
Constraints:
2 <= divisor1, divisor2 <= 10^51 <= uniqueCnt1, uniqueCnt2 < 10^92 <= uniqueCnt1 + uniqueCnt2 <= 10^9
Solution
Approach: Binary Search on the Answer
Guess the maximum value x. Among 1..x, the numbers not divisible by d number x // d * (d - 1) + x % d. A guess works when:
- there are at least
uniqueCnt1numbers not divisible bydivisor1, - there are at least
uniqueCnt2numbers not divisible bydivisor2, - there are at least
uniqueCnt1 + uniqueCnt2numbers not divisible bylcm(divisor1, divisor2), since those are the numbers either array could take, and the two arrays must not overlap.
Feasibility only gets easier as x grows, so binary search for the smallest feasible x.
Complexity: O(log U) time for the search range U, and O(1) space.
from math import gcd
class Solution:
def minimizeSet(
self, divisor1: int, divisor2: int, uniqueCnt1: int, uniqueCnt2: int
) -> int:
def f(x):
cnt1 = x // divisor1 * (divisor1 - 1) + x % divisor1
cnt2 = x // divisor2 * (divisor2 - 1) + x % divisor2
cnt = x // divisor * (divisor - 1) + x % divisor
return (
cnt1 >= uniqueCnt1
and cnt2 >= uniqueCnt2
and cnt >= uniqueCnt1 + uniqueCnt2
)
divisor = divisor1 // gcd(divisor1, divisor2) * divisor2
l, r = 1, 10**10
while l < r:
mid = (l + r) >> 1
if f(mid):
r = mid
else:
l = mid + 1
return l