## Similar Problems

Similar Problems not available

# Minimize The Maximum Of Two Arrays - Leetcode Solution

## Companies:

LeetCode: Minimize The Maximum Of Two Arrays Leetcode Solution

Difficulty: Medium

Topics: math binary-search

Problem Statement: Given two arrays A and B, find the minimum possible value of max(A[i],B[j]) over all i and j.

Solution: One way to solve this problem is to use binary search to find the minimum possible value of max(A[i],B[j]). We can guess a possible value of max(A[i],B[j]) and then check whether this guess is feasible or not. If the guess is too small, we increase it, and if it is too large, we decrease it.

To check whether a guess is feasible or not, we can use two pointers i and j to count the number of elements in A and B that are greater than or equal to the guess. Specifically, we can start with i = 0 and j = 0, and then compare A[i] and B[j]. If A[i] >= guess, then all elements in A from A[i] to A[N-1] are greater than or equal to the guess. Similarly, if B[j] >= guess, then all elements in B from B[j] to B[M-1] are greater than or equal to the guess. Then, we can count the total number of elements greater than or equal to the guess as (N-i) + (M-j). If this count is greater than or equal to (N+M)/2, then the guess is feasible, because it means that at least half the elements in A and B are greater than or equal to the guess.

Here is the pseudocode for this algorithm:

- Use binary search to guess the minimum possible value of max(A[i],B[j]).
- For a given guess, use two pointers i and j to count the number of elements in A and B that are greater than or equal to the guess.
- If the count is greater than or equal to (N+M)/2, then the guess is feasible, and we can try a smaller value.
- Otherwise, the guess is too small, and we can try a larger value.

Here is the actual code in Python:

def min_max_arrays(A, B): # Step 1: Use binary search to find the minimum possible value of max(A[i],B[j]) low = min(A[0], B[0]) high = max(A[-1], B[-1]) while low < high: mid = (low + high) // 2 # Step 2: Use two pointers i and j to count the number of elements >= mid i = 0 j = 0 for x in A: if x >= mid: break i += 1 for y in B: if y >= mid: break j += 1 count = len(A) - i + len(B) - j # Step 3 and 4: Adjust low or high depending on the feasibility of mid if count >= (len(A) + len(B)) // 2: low = mid + 1 else: high = mid return low

# Test the function

A = [1, 2, 3, 4, 5, 6] B = [1, 2, 3] print(min_max_arrays(A, B)) # Output: 3

# Explanation: The possible values of max(A[i],B[j]) are [1, 2, 3]. The number of elements >= 1, 2, and 3 are

# 6, 6, and 3 respectively. Since 6 >= (6+3)//2 and 3 < (6+3)//2, the minimum possible value of max(A[i],B[j]) is 3.

## Minimize The Maximum Of Two Arrays Solution Code

`1`