Find maximum and minimum element of an array

Posted by N.K. Chauhan on Jan 02, 2022

An array A is given, the task is to find minimum and maximum element of A.

Example 1: Find max and min element of: {1 ,2 ,3 ,4 ,5}

Input: {1 ,2 ,3 ,4 ,5}
Output: [1,5]

Example 1: Find max and min element of: {1}

Input: {1}
Output: [1,1]

Example 1: Find max and min element of: {52 ,94 ,3 ,18 ,5}

Input: {52 ,94 ,3 ,18 ,5}
Output: [3,94]


Solutions

Method 1: Linear Search

We can solve this problem in O(n) time using simple linear search, all we need to do is to compare and update each element with min & max variables. Initialise min and max with 0th element and iterate the array from index 1 to length-1.

Complexity

The time complexity of this solution is O(n) and space complexity is O(1).

Related


Program to print Union of two sorted arrays

Print all Subsets (Power Set) of a given array

Print all possible permutations of an Array in O(1) space

Longest substring without repeating characters

Program to print Intersection of two sorted arrays

Count the number of inversions in an array - in O(n log n) time

Two Sum - return index of a pair of array elements with a given sum

Rain water trapping problem - O(n) time & O(n) space

Merge two sorted arrays in O(1) space

Word Break Problem (Using HashMap and DP)

Find a triplet in an array that sums to a given number