Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

# Min and Max

Last Updated on March 28, 2022 by Ria Pathak

### CONCEPTS USED:

Basic Mathematics

Easy

### PROBLEM STATEMENT`(`SIMPLIFIED`)`:

With a given array of size `N`, find the largest (maximum) and smallest (minimum) element from the elements.

See original problem statement here

#### For Example :

``````N = 5
Arr[] = [4, 3, 2, 1, 5]

Maximum element = 5
Minimum element = 1``````

### SOLVING APPROACH:

1. Initialize variables `max_e`, `min_e` as `INT_MIN` and `INT_MAX` respectively.
2. Traverse the array, if the value of current element is greater than `max_e`, update value of `max_e` to the current element’s value. Similarly, if the value of current element is less than `min_e`, update it too.
3. Keep updating variables `max_e` and `min_e`.
4. Post array traversal, we will get our Max and Min elements.

#### NOTE:

`INT_MAX` is a macro that specifies that an integer variable cannot store any value beyond this limit.

`INT_MIN` specifies that an integer variable cannot store any value below this limit.

### SOLUTIONS:

```#include<stdio.h>
#include<limits.h>

void main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
int arr[n];
int max_e = INT_MIN;
int min_e = INT_MAX;
for(int i=0;i<n;i++)
{
scanf("%d",&arr[i]);
if(arr[i]>max_e)
max_e = arr[i];
if(arr[i]<min_e)
min_e = arr[i];
}
printf("%d %d\n",max_e,min_e);
}
}
```
```#include <bits/stdc++.h>
using namespace std;

int main()
{
int t;cin>>t;
while(t--)
{
int n;cin>>n;
int arr[n];
int max_e = INT_MIN;
int min_e = INT_MAX;
for(int i=0;i<n;i++)
{
cin>>arr[i];
if(arr[i]>max_e)
max_e = arr[i];
if(arr[i]<min_e)
min_e = arr[i];
}
cout<<min_e<<" "<<max_e<<"\n";
}
return 0;
}

```
```import java.util.*;
import java.io.*;

public class Main
{
public static void main(String args[]) throws IOException
{
Scanner sc = new Scanner(System.in);
int t;
t = sc.nextInt();
while(t!=0)
{
int n;
n = sc.nextInt();
int arr[] = new int[n];
int max_e = Integer.MIN_VALUE;
int min_e = Integer.MAX_VALUE;
for(int i=0;i<n;i++)
{
arr[i] = sc.nextInt();
if(arr[i]>max_e)
max_e = arr[i];
if(arr[i]<min_e)
min_e = arr[i];

}
System.out.println(min_e + " " + max_e);
t--;
}
}
}

```

[forminator_quiz id="632"]

Space Complexity: O(1)

This article tried to discuss Basic Mathematics. Hope this blog helps you understand and solve the problem. To practice more problems on Basic Mathematics you can check out MYCODE | Competitive Programming.