DEV Community

Jarvish John
Jarvish John

Posted on

CA 06 - Find Maximum and Minimum in an 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.

My Goal

For this problem, my goal was to:

Understand how to traverse an array efficiently
Identify smallest and largest values without sorting
Keep the solution simple and optimal
Avoid unnecessary operations like sorting (which increases complexity)

Solution

I used a single traversal approach to find both minimum and maximum values.

Idea:
Assume the first element is both minimum and maximum
Traverse the array from left to right
Compare each element:
If smaller → update minimum
If larger → update maximum

This way, we solve the problem in one pass.

Solution Code

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

mn = a[0]
mx = a[0]

for x in a:
    if x < mn:
        mn = x
    if x > mx:
        mx = x

print([mn, mx])
Enter fullscreen mode Exit fullscreen mode

Top comments (0)