Given two arrays, how to find the maximum element which is common to both the arrays?
I was thinking of sorting both the arrays(n log n) and then perform the binary search of every element from one sorted array(starting from larger one) in another array until match is found.
eg:
a = [1,2,5,4,3]
b = [9,8,3]
Maximum common element in these array is 3
Can we do better than n log n?
Let dp[i][j] be the longest common subarray of A[i…] and B[j…]. Therefore, for any index i and j, if A[i] is equals to B[j], then dp[i][j] = dp[i+1][j+1] + 1. The maximum of all the element in the array dp[][] will give the maximum length of equal subarrays.
To find the largest element from the array, a simple way is to arrange the elements in ascending order. After sorting, the first element will represent the smallest element, the next element will be the second smallest, and going on, the last element will be the largest element of the array.
With some extra space you could hash in 1 array, then do a contains on each element of the other array keeping track of the biggest value that returns true. Would be O(n).
You can but using O(N)
space.
Just go through the first array and place all elements in a HashTable
. This is O(N)
Then go through the second array keeping track of the current maximum and checking if the element is in the HashTable
. This is also O(N)
.
So total runtime is O(N)
and O(N)
extra space for the HashTable
Example in Java:
public static int getMaxCommon(int[] a, int[] b){
Set<Integer> firstArray = new HashSet<Integer>(Arrays.asList(a));
int currentMax = Integer.MIN_VALUE;
for(Integer n:b){
if(firstArray.contains(n)){
if(currentMax < n){
currentMax = n
}
}
}
return currentMax;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With