#2513

Minimize the Maximum of Two Arrays

Medium
MathBinary SearchNumber TheoryBinary SearchCounting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(log(max))
Space
O(1)
O(1)
💡

Intuition

Time O(log(max))Space O(1)

The optimal approach uses binary search to minimize the maximum integer that can be present in either array. By leveraging the properties of divisibility and counting valid integers, we can efficiently find the smallest maximum.

⚙️

Algorithm

5 steps
  1. 1Step 1: Define a function to count how many valid integers can be added to both arrays up to a given maximum value.
  2. 2Step 2: Use binary search to find the minimum possible maximum integer that satisfies the conditions for both arrays.
  3. 3Step 3: Set the search range from 1 to a high enough value (like 2 * (uniqueCnt1 + uniqueCnt2)).
  4. 4Step 4: For each mid-point in the binary search, check if the counts of valid integers meet the unique count requirements.
  5. 5Step 5: Adjust the search range based on whether the current mid-point is valid.
solution.py18 lines
1# Full working Python code
2
3def count_valid(max_num, divisor1, divisor2):
4    count1 = max_num // divisor1
5    count2 = max_num // divisor2
6    count_common = max_num // (divisor1 * divisor2)
7    return (max_num - count1) + (max_num - count2) - count_common
8
9def minMax(divisor1, divisor2, uniqueCnt1, uniqueCnt2):
10    left, right = 1, 2 * (uniqueCnt1 + uniqueCnt2)
11    while left < right:
12        mid = (left + right) // 2
13        if count_valid(mid, divisor1, divisor2) >= uniqueCnt1 + uniqueCnt2:
14            right = mid
15        else:
16            left = mid + 1
17    return left
18

Complexity note: The complexity is O(log(max)) where max is the maximum number we are searching up to, due to the binary search. The counting function runs in constant time.

  • 1Understanding how to count valid integers based on divisibility is crucial.
  • 2Binary search can significantly reduce the time complexity for problems involving finding minimum or maximum values.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.