DEV Community

Jonah Blessy
Jonah Blessy

Posted on

CA 06 - Find the Maximum and Minimum Element in the Array

Problem Statement:
Given an array arr[]. Your task is to find the minimum and maximum elements in the array.

Examples:

Input: arr[] = [1, 4, 3, 5, 8, 6]
Output: [1, 8]
Explanation: minimum and maximum elements of array are 1 and 8.
Input: arr[] = [12, 3, 15, 7, 9]
Output: [3, 15]
Explanation: minimum and maximum element of array are 3 and 15.
Constraints:
1 ≤ arr.size() ≤ 105
1 ≤ arr[i] ≤ 109

Brute force solution:
Brute force approach would be to input an array then for finding minimum and maximum values, start by traversing from the first value of the array. Iterate through each element, comparing with min_val and max_val. If the array value is less than min_val, update min_val to array value. Similarly, if array value is greater than max_val update max_val to array value.

Example:
arr = [12, 3, 15, 7, 9]
min_val = arr[0]
max_val = arr[0]
for num in arr:
if num < min_val:
min_val = num
if num > max_val:
max_val = num
print([min_val, max_val])

Output:
[3,15]

Solution with built-in functions:
This makes use of the python built-in functions max() and min() to get the maximum and minimum values of the array respectively.

arr = [1, 4, 3, 5, 8, 6]
min_val = min(arr)
max_val = max(arr)
print([min_val, max_val])

Output:
[1, 8]

Top comments (0)