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

 Min and Max in Array

Given an array arr[]. Your task is to find the minimum and maximum elements in the array.
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.

CODE:

    The first element of the array is appointed as the min and max value. Then the whole list is traversed and each element is checked with the current min and max element, if it is otherwise then the new min or max element is set to the current element. Here the first value need not be checked, but avoiding it is trivial and does not affect much hence we leave it as such.

Time Complexity: O(n)

class Solution:
    def getMinMax(self, arr):
        minarr = arr[0]
        maxarr = arr[0]
        for i in arr:
            if i > maxarr:
                maxarr = i
            elif i<minarr:
                minarr = i
        return [minarr,maxarr]

Comments

Popular posts from this blog

CA 04 - Two Sum & Sorted Two Sum

CA 05 - Reverse the array

CA 21 - Basic Select SQL Queries