DEV Community

Tharunya K R
Tharunya K R

Posted on

Find Minimum and Maximum Elements in an Array Using Python

Find Minimum and Maximum Elements in an Array (Python)
Problem

Given an array arr[], find the minimum and maximum elements.

Example

Input

arr = [1, 4, 3, 5, 8, 6]

Output

[1, 8]

Explanation:
Minimum = 1, Maximum = 8

Approach
Assume the first element as minimum and maximum.
Traverse the array.
Update minimum if a smaller value is found.
Update maximum if a larger value is found.

Python Code

class Solution:
def getMinMax(self, arr):
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

    return [min_val, max_val]
Enter fullscreen mode Exit fullscreen mode

Output
[1, 8]

Top comments (0)