Find Minimum and Maximum Element in an Array
Examples
Input
arr = [3, 5, 1, 8, 2]
Output
Minimum element is 1
Maximum element is 8
Input
arr = [7, 7, 7, 7]
Output
Minimum element is 7
Maximum element is 7
Approach 1 Simple Traversal
The idea is to traverse the array and keep track of the minimum and maximum values.
Steps
1 Initialize min and max with the first element
2 Traverse the array from second element
3 If current element is greater than max update max
4 If current element is smaller than min update min
Code
```python id="gfg1"
def getMinMax(arr):
min_val = arr[0]
max_val = arr[0]
for i in range(1, len(arr)):
if arr[i] > max_val:
max_val = arr[i]
elif arr[i] < min_val:
min_val = arr[i]
return min_val, max_val
---
## Approach 2 Using Built in Functions
```python id="gfg2"
def getMinMax(arr):
return min(arr), max(arr)
Explanation
In the first method, we manually compare each element with current minimum and maximum values. In the second method, Python provides direct functions to get the result.
Expected Output
Input
arr = [3, 5, 1, 8, 2]
Output
1 8
Conclusion
This problem helps in understanding array traversal and comparison. It is one of the basic problems asked in coding interviews and is useful in many real world scenarios.
Practice this problem with different inputs to improve your understanding.
Top comments (0)