Minimize the Maximum of Two Arrays - Problem

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:

  • arr1 contains uniqueCnt1 distinct positive integers, each of which is not divisible by divisor1.
  • arr2 contains uniqueCnt2 distinct positive integers, each of which is not divisible by divisor2.
  • No integer is present in both arr1 and arr2.

Given divisor1, divisor2, uniqueCnt1, and uniqueCnt2, return the minimum possible maximum integer that can be present in either array.

Input & Output

Example 1 — Basic Case
$ Input: divisor1 = 2, divisor2 = 3, uniqueCnt1 = 1, uniqueCnt2 = 1
Output: 3
💡 Note: We can put 1 in arr1 (not divisible by 2) and 2 in arr2 (not divisible by 3). The maximum is 3, but we only use up to 2, so we need to check if 2 works. With maxVal=2: arr1 can use {1}, arr2 can use {1} but 1 is already in arr1. So maxVal=3: arr1 can use {1,3}, take 1. arr2 can use {1,2}, take 2. Maximum element is 2, but minimum possible maximum is 3.
Example 2 — Larger Requirements
$ Input: divisor1 = 3, divisor2 = 5, uniqueCnt1 = 2, uniqueCnt2 = 1
Output: 4
💡 Note: For maxVal=4: Numbers not divisible by 3: {1,2,4}. Numbers not divisible by 5: {1,2,3,4}. arr1 needs 2 elements from {1,2,4}, take {1,2}. arr2 needs 1 element from {1,2,3,4} excluding {1,2}, can take {3}. All requirements satisfied with maximum 4.
Example 3 — Same Divisors
$ Input: divisor1 = 2, divisor2 = 2, uniqueCnt1 = 1, uniqueCnt2 = 1
Output: 3
💡 Note: Both arrays need elements not divisible by 2. Available: {1,3,5,...}. arr1 takes 1, arr2 takes 3. Minimum maximum is 3.

Constraints

  • 2 ≤ divisor1, divisor2 ≤ 105
  • 1 ≤ uniqueCnt1, uniqueCnt2 ≤ 109

Visualization

Tap to expand
Minimize Maximum: Two Arrays with Divisibility Constraintsarr1 (size 1)arr2 (size 1)Not divisible by 2Not divisible by 3Available numbers with maxVal = 3:For arr1: {1, 3}For arr2: {1, 2}Solution: arr1 = [1], arr2 = [2]Minimum Maximum = 3
Understanding the Visualization
1
Input
divisor1=2, divisor2=3, uniqueCnt1=1, uniqueCnt2=1
2
Process
Find minimum maximum allowing both arrays to be filled
3
Output
Minimum possible maximum = 3
Key Takeaway
🎯 Key Insight: Binary search on the maximum value while using inclusion-exclusion to count valid numbers efficiently
Asked in
Google 25 Microsoft 18 Amazon 15
12.5K Views
Medium Frequency
~25 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen