Reputation: 1
I need to find maximum element from two arrays
int arr1[]={20,65,23056,67,678};
int arr2[]={76,23,4545,98,90909};
My code is giving output but i think it's complexity is high.Below are my code.Is it good or it need improvement?
int arr1[]={20,65,23056,67,678};
int arr2[]={76,23,4545,98,90909};
int len1=arr1.length;
int len2=arr2.length;
int max1=arr1[0];
for(int i=0;i<len1;i++){
if(arr1[i]>max1){
max1=arr1[i];
}
}
int max2=arr2[0];
for(int j=0;j<len2;j++){
if(arr2[j]>max2){
max2=arr2[j];
}
}
if(max1>max2){
System.out.print("max element is:"+max1);
}
else{
System.out.print("Max element is: "+max2);
}
Output :- 90909
Upvotes: 0
Views: 5021
Reputation: 386
Other answers here focus on Streams (which is perfectly fine - and acceptable).
However, if you have limitations on usage of stream (JDK 7 and earlier), you could put the arrays in a TreeSet
with Collections.reverseOrder
to sort the elements in descending order. The 0th
index will be the largest or mac element from the union of the arrays.
Edit: Note that TreeSet
doesn't persist duplicates, so you're better off than storing duplicates in arrays. In the worst case, if two arrays of 5 elements
each contained 9 duplicates
, the TreeSet
would only house 2 elemens
(the unique one and the other being the duplicate one), as against two arrays containing 10 elements
.
Upvotes: 0
Reputation: 3052
Even if you don't want to deal with streams, you can still improve it a bit:
int arr1[] = { 20, 65, 23056, 67, 678 };
int arr2[] = { 76, 23, 4545, 98, 90909 };
int len = arr1.length > arr2.length ? arr1.length : arr2.length;
int max = 0;
for (int i = 0; i < len; i++) {
if (arr1.length > i && arr1[i] > max) {
max = arr1[i];
}
if (arr2.length > i && arr2[i] > max) {
max = arr2[i];
}
}
System.out.print("max element is:" + max);```
Upvotes: 0
Reputation: 16910
You can use Java streams to achieve this. If you want to avoid boxing values to Integer
and you want to get primitive integer directly use IntStream::concat
and and IntStream::of
:
int[] arr1 = {20, 65, 23056, 67, 678};
int[] arr2 = {76, 23, 4545, 98, 90909};
int max = IntStream
.concat(IntStream.of(arr1), IntStream.of(arr2))
.max()
.getAsInt();
Upvotes: 4
Reputation: 189
If we consider the length of the first and second arrays as n and m respectively. Your solution is taking the complexity of O(n+m). It's the best case, as the arrays are not sorted.
Upvotes: 0
Reputation: 319
Try this
Integer arr1[]={20,65,23056,67,678};
Integer arr2[]={76,23,4545,98,90909};
Integer max = Stream.concat(Arrays.stream(arr1), Arrays.stream(arr2)).max(Comparator.comparing(Integer::valueOf)).get();
Upvotes: 5