DSA(Array): Find the maximum and minimum element in an array
Soham
Posted on May 13, 2023
Given an array A of size N of integers. Your task is to find the minimum and maximum elements in the array.
Example 1:
Input:
N = 6
A[] = {3, 2, 1, 56, 10000, 167}
Output:
min = 1, max = 10000
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
Explanation and code:
In this section we will discuss the most efficient approach for solving this type of problem.
What I am going to do:
At first take a vector which will store the elements of our array. After that we will sort the vector using sort() function.In this way we will get our modified array in descending order.Now we take the pair (long long as mentioned earlier). Now also take two variables named max and min long long data type.
After that we can observer that our array already in descending order so most greater element in the last position that means n-1 and the smallest element in 0th position.(based on the 0th based indexing) now if we can say max store the last element and min will store first index element.
Sample Code:
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
#define ll long long
pair<long long, long long> getMinMax(long long a[], int n) ;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
ll a[n];
for (int i = 0; i < n; i++) cin >> a[i];
pair<ll, ll> pp = getMinMax(a, n);
cout << pp.first << " " << pp.second << endl;
}
return 0;
}
// } Driver Code Ends
pair<long long, long long> getMinMax(long long a[], int n) {
vector<int>st;
for(int i=0;i<n;i++){
st.push_back(a[i]);
}
sort(st.begin(),st.end());
pair<long long,long long>ans;
long long min,max;
max = st[n-1];
min = st[0];
ans = {min,max};
return ans;
}
Output:
For Input:
6
3 2 1 56 1000 167
Your Output:
1 1000
Posted on May 13, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.