To Find the max & min elements in a array

Published: (March 18, 2026 at 03:23 PM EDT)
1 min read
Source: Dev.to

Source: Dev.to

Approach

To find the minimum and maximum elements in an array without using built‑in min or max functions, initialize both min and max with the first element of the array. Then iterate through the rest of the array, updating min when a smaller value is encountered and updating max when a larger value is found. Finally, return the two values as a list.

Code

def minmax(arr):
    min_val = arr[0]
    max_val = arr[0]

    for i in range(1, len(arr)):
        if arr[i]  max_val:
            max_val = arr[i]
    return [min_val, max_val]

arr = [12, 3, 15, 7, 9]
print(minmax(arr))
0 views
Back to Blog

Related posts

Read more »

Next Permutation

Problem Description The task is to compute the next permutation of a given array of numbers. A permutation is a rearrangement of the same elements, and the nex...