DEV Community

Suruthika
Suruthika

Posted on

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

Problem
Min and Max in Array
You are given an array arr[] of integers.
Your task is to find the minimum and maximum elements in the array.

  • Input: [1, 4, 3, 5, 8, 6] → Output: [1, 8]
  • Input: [12, 3, 15, 7, 9] → Output: [3, 15]

Approach

We can solve this by scanning the array once and keeping track of two values:

  • min_val → stores the smallest element
  • max_val → stores the largest element

Steps:

  • Initialize both min_val and max_val with the first element
  • Traverse the array:

    • Update min_val if a smaller element is found
    • Update max_val if a larger element is found

This way, we find both values in a single pass.

Complexity:

  • Time Complexity: O(n)
  • Space Complexity: O(1)

Code

def findMinMax(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]
arr = [1, 4, 3, 5, 8, 6]
print(findMinMax(arr))
Enter fullscreen mode Exit fullscreen mode

Top comments (0)