Given an array A of size N of integers. Your task is to find the minimum and maximum element in the array.
This question to find minimum and maximum element in an array is taken from GeeksforGeeks platform .
Example 1:
Input:
N = 6
A[] = {3, 2, 1, 56, 10000, 167}
Output:
min = 1, max = 10000
Example 2:
Input:
N = 5
A[] = {1, 345, 234, 21, 56789}
Output:
min = 1, max = 56789
Your Task:
You don’t need to read input or print anything. Your task is to complete the function getMinMax() which takes the array A[] and its size N as inputs and returns the minimum and maximum element of the array.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
Constraints:
1 <= N <= 105
1 <= Ai <=1012
Solution in Java
//{ Driver Code Starts
//Initial Template for Java
import java.util.*;
import java.lang.*;
import java.io.*;
class pair
{
long first, second;
public pair(long first, long second)
{
this.first = first;
this.second = second;
}
}
class GFG {
public static void main(String[] args) throws IOException
{
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
int t =
Integer.parseInt(br.readLine().trim()); // Inputting the testcases
while(t-->0)
{
long n = Long.parseLong(br.readLine().trim());
long a[] = new long[(int)(n)];
// long getAnswer[] = new long[(int)(n)];
String inputLine[] = br.readLine().trim().split(" ");
for (int i = 0; i < n; i++) {
a[i] = Long.parseLong(inputLine[i]);
}
Compute obj = new Compute();
pair product = obj.getMinMax(a, n);
System.out.println(product.first+" "+product.second);
}
}
}
// } Driver Code Ends
//User function Template for Java
/*
class pair
{
long first, second;
public pair(long first, long second)
{
this.first = first;
this.second = second;
}
}*/
class Compute
{
static pair getMinMax(long a[], long n)
{
int i; long max=0;
for(i=0;i<n;i++)
{
if(a[i]>max)
{
max=a[i];
}
}
long min=a[0];
for(i=0;i<n;i++)
{
if(min>a[i])
{
min=a[i];
}
}
return new pair(min,max);
}
}
Thank you for reading this article so far, if you know some other way to write this program then you can leave a comment here or mail us at technonamecontact@gmail.com, So anyone can a get chance to publish their code on our website. As a result, one can improve knowledge and spread it to others
Please check most asked programming questions of strings with examples by clicking here, after that you might get a deep knowledge about string operations, in short, it will be helpful in clearing the interview.
For understanding the most important concept of data structures in an easy way you can check this article on our website.
Thanks for reading this article so far. If you like this article, then please share it with your friends and colleagues. If you have any questions or feedback, then please drop a note.
You can also follow us on Twitter for daily updates.