DEV Community

Dharani
Dharani

Posted on

Finding Maximum and Minimum Element in an Array

Introduction

In programming, finding the maximum and minimum elements in an array is a basic and important problem. It helps us understand loops, comparisons, and problem-solving techniques.


Problem Statement

Given an array of integers, find:

  • The minimum (smallest) element
  • The maximum (largest) element

Approach

We can solve this problem using a simple method:

  1. Assume the first element as both minimum and maximum
  2. Traverse through the array
  3. Compare each element with current min and max
  4. Update values accordingly

Python Code

def find_min_max(arr):
minimum = arr[0]
maximum = arr[0]

for num in arr:
if num < minimum:
minimum = num
if num > maximum:
maximum = num

return minimum, maximum

Enter fullscreen mode Exit fullscreen mode




Example usage

arr = [10, 5, 20, 8, 2]
min_val, max_val = find_min_max(arr)

print("Minimum:", min_val)
print("Maximum:", max_val)

ouput:

Minimum : 2
Maximum : 20

Top comments (0)