Program to find the minimum (or maximum) element of an array
Last Updated :
10 Apr, 2025
Given an array, write functions to find the minimum and maximum elements in it.
Examples:
Input: arr[] = [1, 423, 6, 46, 34, 23, 13, 53, 4]
Output: Minimum element of array: 1
Maximum element of array: 423
Input: arr[] = [2, 4, 6, 7, 9, 8, 3, 11]
Output: Minimum element of array: 2
Maximum element of array: 11
Approach: Using inbuilt sort() function - O(n logn) time and O(1) space
The simplest and most efficient way to find the minimum and maximum values in a collection is by sorting the collection. Many programming languages provide an inbuilt s
ort() function that sorts collections (like arrays, lists, etc.) in ascending order. Once the collection is sorted, the minimum value is at the 0th position, and the maximum value is at the nth position (where n
is the size of the collection).
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> arr = {1, 423, 6, 46, 34, 23, 13, 53, 4};
// Implemented inbuilt function to sort the vector
sort(arr.begin(), arr.end());
// After sorting, the value at the 0th position will be the minimum
// and the last position will be the maximum
cout << "Minimum element of array: " << arr[0] << endl;
cout<< "Maximum element of array: " << arr[arr.size() - 1] << endl;
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int main() {
int arr[] = {1, 423, 6, 46, 34, 23, 13, 53, 4};
int n = sizeof(arr) / sizeof(arr[0]);
// Implemented inbuilt function to sort the array
qsort(arr, n, sizeof(int), compare);
// After sorting, the value at the 0th position will be the minimum
// and the last position will be the maximum
printf("Minimum element of array: %d\n", arr[0]);
printf("Maximum element of array: %d\n", arr[n - 1]);
return 0;
}
Java
import java.util.Arrays;
public class GfG {
public static void main(String[] args) {
int[] arr = {1, 423, 6, 46, 34, 23, 13, 53, 4};
// Implemented inbuilt function to sort the array
Arrays.sort(arr);
// After sorting, the value at the 0th position will be the minimum
// and the last position will be the maximum
System.out.println("Minimum element of array: " + arr[0]);
System.out.println("Maximum element of array: " + arr[arr.length - 1]);
}
}
Python
arr = [1, 423, 6, 46, 34, 23, 13, 53, 4]
# Implemented inbuilt function to sort the list
arr.sort()
# After sorting, the value at the 0th position will be the minimum
# and the last position will be the maximum
print("Minimum element of array:", arr[0])
print("Maximum element of array:", arr[-1])
C#
using System;
using System.Linq;
class GfG {
static void Main() {
int[] arr = {1, 423, 6, 46, 34, 23, 13, 53, 4};
// Implemented inbuilt function to sort the array
Array.Sort(arr);
// After sorting, the value at the 0th position will be the minimum
// and the last position will be the maximum
Console.WriteLine("Minimum element of array: " + arr[0]);
Console.WriteLine("Maximum element of array: " + arr[arr.Length - 1]);
}
}
JavaScript
const arr = [1, 423, 6, 46, 34, 23, 13, 53, 4];
// Implemented inbuilt function to sort the array
arr.sort((x, y) => x - y);
// After sorting, the value at the 0th position will be the minimum
// and the last position will be the maximum
console.log("Minimum element of array:", arr[0]);
console.log("Maximum element of array:", arr[arr.length - 1]);
OutputMinimum element of array: 1
Maximum element of array: 423
Approach: Linear Scan Method - O(n) time and O(1) space
The approach used here is a linear scan to find the minimum and maximum values in a collection, specifically in a vector
in this case. We start by assuming the first element of the collection is both the minimum and the maximum. Then, as we iterate through the collection, we compare each element to the current minimum and maximum. If an element is smaller than the current minimum, we update the minimum; if it's larger than the current maximum, we update the maximum. This continues for all elements in the collection, and at the end of the loop, we have the minimum and maximum values.
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int getMin(const vector<int>& arr)
{
int res = arr[0];
for (int i = 1; i < arr.size(); i++)
res = min(res, arr[i]);
return res;
}
int getMax(const vector<int>& arr)
{
int res = arr[0];
for (int i = 1; i < arr.size(); i++)
res = max(res, arr[i]);
return res;
}
int main()
{
vector<int> arr = {1, 423, 6, 46, 34, 23, 13, 53, 4};
cout << "Minimum element of array: " << getMin(arr) << "\n";
cout << "Maximum element of array: " << getMax(arr) << "\n";
return 0;
}
C
#include <stdio.h>
#include <limits.h>
int getMin(int arr[], int size) {
int res = arr[0];
for (int i = 1; i < size; i++)
if (arr[i] < res) res = arr[i];
return res;
}
int getMax(int arr[], int size) {
int res = arr[0];
for (int i = 1; i < size; i++)
if (arr[i] > res) res = arr[i];
return res;
}
int main() {
int arr[] = {1, 423, 6, 46, 34, 23, 13, 53, 4};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Minimum element of array: %d\n", getMin(arr, size));
printf("Maximum element of array: %d\n", getMax(arr, size));
return 0;
}
Java
import java.util.Arrays;
public class GfG {
public static int getMin(int[] arr) {
int res = arr[0];
for (int i = 1; i < arr.length; i++)
res = Math.min(res, arr[i]);
return res;
}
public static int getMax(int[] arr) {
int res = arr[0];
for (int i = 1; i < arr.length; i++)
res = Math.max(res, arr[i]);
return res;
}
public static void main(String[] args) {
int[] arr = {1, 423, 6, 46, 34, 23, 13, 53, 4};
System.out.println("Minimum element of array: " + getMin(arr));
System.out.println("Maximum element of array: " + getMax(arr));
}
}
Python
def get_min(arr):
res = arr[0]
for i in arr[1:]:
res = min(res, i)
return res
def get_max(arr):
res = arr[0]
for i in arr[1:]:
res = max(res, i)
return res
arr = [1, 423, 6, 46, 34, 23, 13, 53, 4]
print("Minimum element of array:", get_min(arr))
print("Maximum element of array:", get_max(arr))
C#
using System;
class GfG {
static int GetMin(int[] arr) {
int res = arr[0];
for (int i = 1; i < arr.Length; i++)
res = Math.Min(res, arr[i]);
return res;
}
static int GetMax(int[] arr) {
int res = arr[0];
for (int i = 1; i < arr.Length; i++)
res = Math.Max(res, arr[i]);
return res;
}
static void Main() {
int[] arr = {1, 423, 6, 46, 34, 23, 13, 53, 4};
Console.WriteLine("Minimum element of array: " + GetMin(arr));
Console.WriteLine("Maximum element of array: " + GetMax(arr));
}
}
JavaScript
function getMin(arr) {
let res = arr[0];
for (let i = 1; i < arr.length; i++)
res = Math.min(res, arr[i]);
return res;
}
function getMax(arr) {
let res = arr[0];
for (let i = 1; i < arr.length; i++)
res = Math.max(res, arr[i]);
return res;
}
let arr = [1, 423, 6, 46, 34, 23, 13, 53, 4];
console.log("Minimum element of array: " + getMin(arr));
console.log("Maximum element of array: " + getMax(arr));
OutputMinimum element of array: 1
Maximum element of array: 423
Approach: Recursive Approach - O(n) time and O(n) space
The approach used in the code is a recursive solution to find the minimum and maximum values in a collection (in this case, a vector).
Here's how it works:
1. Base Case: For each function (getMin
and getMax
), the base case is when there's only one element left in the vector (n == 1
). In this case, the function simply returns that element because it's both the minimum and maximum.
2. Recursive Step: If there are more than one element, the function compares the current element (arr[n-1]
) with the result of the recursive call on the rest of the vector (getMin(arr, n-1)
or getMax(arr, n-1)
):
- For
getMin
: The function returns the smaller of the current element (arr[n-1]
) and the result of the recursive call, which finds the minimum in the rest of the array. - For
getMax
: Similarly, it returns the larger of the current element and the result of the recursive call, which finds the maximum in the remaining array.
3. End Result: The recursion continues until only one element remains, and at each recursive step, the function builds up the final minimum or maximum value by comparing and returning the smallest or largest values found so far.
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int getMin(const vector<int>& arr, int n)
{
// If there is a single element, return it.
// Else, return the minimum of the first element and the minimum of the remaining array.
if (n == 1) {
return arr[0];
}
return min(arr[n - 1], getMin(arr, n - 1));
}
int getMax(const vector<int>& arr, int n)
{
// If there is a single element, return it.
// Else, return the maximum of the first element and the maximum of the remaining array.
if (n == 1) {
return arr[0];
}
return max(arr[n - 1], getMax(arr, n - 1));
}
int main()
{
vector<int> arr = {1, 423, 6, 46, 34, 23, 13, 53, 4};
int n = arr.size();
cout << "Minimum element of array: " << getMin(arr, n) << "\n";
cout << "Maximum element of array: " << getMax(arr, n) << "\n";
return 0;
}
C
#include <stdio.h>
#include <limits.h>
int getMin(int arr[], int n) {
// If there is a single element, return it.
// Else, return the minimum of the first element and the minimum of the remaining array.
if (n == 1) {
return arr[0];
}
return (arr[n - 1] < getMin(arr, n - 1)) ? arr[n - 1] : getMin(arr, n - 1);
}
int getMax(int arr[], int n) {
// If there is a single element, return it.
// Else, return the maximum of the first element and the maximum of the remaining array.
if (n == 1) {
return arr[0];
}
return (arr[n - 1] > getMax(arr, n - 1)) ? arr[n - 1] : getMax(arr, n - 1);
}
int main() {
int arr[] = {1, 423, 6, 46, 34, 23, 13, 53, 4};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Minimum element of array: %d\n", getMin(arr, n));
printf("Maximum element of array: %d\n", getMax(arr, n));
return 0;
}
Java
import java.util.Arrays;
public class MinMax {
public static int getMin(int[] arr, int n) {
// If there is a single element, return it.
// Else, return the minimum of the first element and the minimum of the remaining array.
if (n == 1) {
return arr[0];
}
return Math.min(arr[n - 1], getMin(arr, n - 1));
}
public static int getMax(int[] arr, int n) {
// If there is a single element, return it.
// Else, return the maximum of the first element and the maximum of the remaining array.
if (n == 1) {
return arr[0];
}
return Math.max(arr[n - 1], getMax(arr, n - 1));
}
public static void main(String[] args) {
int[] arr = {1, 423, 6, 46, 34, 23, 13, 53, 4};
int n = arr.length;
System.out.println("Minimum element of array: " + getMin(arr, n));
System.out.println("Maximum element of array: " + getMax(arr, n));
}
}
Python
def getMin(arr, n):
# If there is a single element, return it.
# Else, return the minimum of the first element and the minimum of the remaining array.
if n == 1:
return arr[0]
return min(arr[n - 1], getMin(arr, n - 1))
def getMax(arr, n):
# If there is a single element, return it.
# Else, return the maximum of the first element and the maximum of the remaining array.
if n == 1:
return arr[0]
return max(arr[n - 1], getMax(arr, n - 1))
arr = [1, 423, 6, 46, 34, 23, 13, 53, 4]
n = len(arr)
print("Minimum element of array:", getMin(arr, n))
print("Maximum element of array:", getMax(arr, n))
C#
using System;
class MinMax {
public static int GetMin(int[] arr, int n) {
// If there is a single element, return it.
// Else, return the minimum of the first element and the minimum of the remaining array.
if (n == 1) {
return arr[0];
}
return Math.Min(arr[n - 1], GetMin(arr, n - 1));
}
public static int GetMax(int[] arr, int n) {
// If there is a single element, return it.
// Else, return the maximum of the first element and the maximum of the remaining array.
if (n == 1) {
return arr[0];
}
return Math.Max(arr[n - 1], GetMax(arr, n - 1));
}
public static void Main() {
int[] arr = {1, 423, 6, 46, 34, 23, 13, 53, 4};
int n = arr.Length;
Console.WriteLine("Minimum element of array: " + GetMin(arr, n));
Console.WriteLine("Maximum element of array: " + GetMax(arr, n));
}
}
JavaScript
function getMin(arr, n) {
// If there is a single element, return it.
// Else, return the minimum of the first element and the minimum of the remaining array.
if (n === 1) {
return arr[0];
}
return Math.min(arr[n - 1], getMin(arr, n - 1));
}
function getMax(arr, n) {
// If there is a single element, return it.
// Else, return the maximum of the first element and the maximum of the remaining array.
if (n === 1) {
return arr[0];
}
return Math.max(arr[n - 1], getMax(arr, n - 1));
}
const arr = [1, 423, 6, 46, 34, 23, 13, 53, 4];
const n = arr.length;
console.log("Minimum element of array: " + getMin(arr, n));
console.log("Maximum element of array: " + getMax(arr, n));
OutputMinimum element of array: 1
Maximum element of array: 423
Approach: Using Inbuilt Functions - O(n) time and O(1) space
The approach involves using inbuilt functions to find the minimum and maximum elements in a collection, such as an array or a vector. These functions work by scanning through the entire collection and comparing each element to determine the smallest or largest value.
- Minimum element: The function compares each element and returns the smallest one.
- Maximum element: The function compares each element and returns the largest one.
C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int getMin(const vector<int>& arr)
{
return *min_element(arr.begin(), arr.end());
}
int getMax(const vector<int>& arr)
{
return *max_element(arr.begin(), arr.end());
}
int main()
{
vector<int> arr = {1, 423, 6, 46, 34, 23, 13, 53, 4};
// Find and print the minimum and maximum elements
cout << "Minimum element of array: " << getMin(arr) << "\n";
cout << "Maximum element of array: " << getMax(arr) << "\n";
return 0;
}
C
#include <stdio.h>
#include <limits.h>
int getMin(int arr[], int size) {
int min = INT_MAX;
for (int i = 0; i < size; i++) {
if (arr[i] < min) {
min = arr[i];
}
}
return min;
}
int getMax(int arr[], int size) {
int max = INT_MIN;
for (int i = 0; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int main() {
int arr[] = {1, 423, 6, 46, 34, 23, 13, 53, 4};
int size = sizeof(arr) / sizeof(arr[0]);
// Find and print the minimum and maximum elements
printf("Minimum element of array: %d\n", getMin(arr, size));
printf("Maximum element of array: %d\n", getMax(arr, size));
return 0;
}
Java
import java.util.Arrays;
public class Main {
public static int getMin(int[] arr) {
return Arrays.stream(arr).min().getAsInt();
}
public static int getMax(int[] arr) {
return Arrays.stream(arr).max().getAsInt();
}
public static void main(String[] args) {
int[] arr = {1, 423, 6, 46, 34, 23, 13, 53, 4};
// Find and print the minimum and maximum elements
System.out.println("Minimum element of array: " + getMin(arr));
System.out.println("Maximum element of array: " + getMax(arr));
}
}
Python
def getMin(arr):
return min(arr)
def getMax(arr):
return max(arr)
arr = [1, 423, 6, 46, 34, 23, 13, 53, 4]
# Find and print the minimum and maximum elements
print("Minimum element of array:", getMin(arr))
print("Maximum element of array:", getMax(arr))
C#
using System;
using System.Linq;
class GfG {
static int GetMin(int[] arr) {
return arr.Min();
}
static int GetMax(int[] arr) {
return arr.Max();
}
static void Main() {
int[] arr = {1, 423, 6, 46, 34, 23, 13, 53, 4};
// Find and print the minimum and maximum elements
Console.WriteLine("Minimum element of array: " + GetMin(arr));
Console.WriteLine("Maximum element of array: " + GetMax(arr));
}
}
JavaScript
function getMin(arr) {
return Math.min(...arr);
}
function getMax(arr) {
return Math.max(...arr);
}
const arr = [1, 423, 6, 46, 34, 23, 13, 53, 4];
// Find and print the minimum and maximum elements
console.log("Minimum element of array:", getMin(arr));
console.log("Maximum element of array:", getMax(arr));
OutputMinimum element of array: 1
Maximum element of array: 423
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem