Find maximum and minimum element of an array

Posted by on Mar 31, 2024

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


Minimize the difference between the heights of smallest and highest tower

Segregate 0s and 1s in an array (Sort an array of 0s and 1s)

Segregate 0s, 1s and 2s in an array (Sort an array of 0s, 1s and 2s)

Program to right rotate an array by 'k' elements

Move all negative numbers to beginning of the array

Find largest sum contiguous sub-array (Kadane's Algorithm)

Maximum Product Subarray (Modified Kadane's Algorithm)

Alternating +ve & -ve in array in O(1) time (maintaining order)

Find duplicates in O(n) time and O(n) extra space.

Find duplicates in O(n) time and O(1) extra space