Problem Statement
Given an array arr[], the task is to find the minimum and maximum elements in the array.
Example
Input:
[1, 4, 3, 5, 8, 6]
Output:
[1, 8]
Explanation:
The smallest element in the array is 1, and the largest element is 8.
*Approach *
To solve this problem efficiently:
Assume the first element is both minimum and maximum
Traverse the array
Compare each element
If smaller, update minimum
If larger, update maximum
Python code
class Solution:
def getMinMax(self, arr):
minimum = arr[0]
maximum = arr[0]
for num in arr:
if num < minimum:
minimum = num
if num > maximum:
maximum = num
return [minimum, maximum]
Conclusion
Finding the minimum and maximum in an array is a fundamental programming problem. It helps in understanding array traversal and comparison logic, which are widely used in real-world applications.
Top comments (0)