![]() |
VOOZH | about |
Given two empty arrays arr1[] and arr2[]. You need to add positive integers to these arrays such that they satisfy the following conditions:
Given the values of d1, d2, k1, and k2, the task is to return the minimum possible maximum value that can be present in either arr1 or arr2.
Example:
Input: d1 = 2, d2 = 7, k1 = 1, k2 = 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.Input: d1 = 3, d2 = 5, k1 = 2, k2 = 1
Output: 3
Explanation:
Here arr1 = [1,2], and arr2 = [3] satisfy all conditions. Since the maximum value is 3, we return it.
Approach:
When you have to minimise/maximise, there's a very high chance you can binary search on the answer. Here if we know a number X provides us enough numbers to fulfill both conditions, then we can simply look for a number smaller than X which might satisfy the condition, if not we will look for a larger number. Now the question is to just check if a number X satisfies the condition or not.
Now to check if a number X satisfies the condition or not, we will first calculate how many numbers are there from 1...X that are divisible by d1 and d2. We can find out this by dividing X by d1, i.e. divisibleByD1 = X / d1. Then we can do the same for d2, i.e. divisibleByD2 = X / d2. Now the number of integers that we can add to the first array are elements1 = X - divisibleByD1 and number of elements we can add to the second array are elements2 = X - divisibleByD2. If you notice here there might be an overlap. For e.g. d1 = 4 and d2 = 6 and X = 13. Here divisibleByD1 = 3 { 4, 8, 12 } and divisibleByD2 = 2 { 6, 12 }. These are the elements that we cannot use in either array1 or array2. But there's an overlap of 12 which we can't use in either of the arrays but we've calculated it twice. To solve this, we will also calculate the number of elements divisible by both d1 and d2 (which is number of elements divisible by lcm(d1, d2)) (this finds out the overlapping elements). Now X will satisfy the condition if k1 <= elements1 && k2 <= elements2 && k1 + k2 <= X - (X / LCM).
Steps-by-step approach:
Below is the implementation of the above approach:
Minimum number of elements: 4
Time complexity: O(k1+ k2)
Auxiliary Space: O(1)