Problem Statement:
Given an array arr[]. Your task is to find the minimum and maximum elements in the array.
Examples:
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.
Constraints:
1 ≤ arr.size() ≤ 105
1 ≤ arr[i] ≤ 109
Brute force solution:
- I first thought of built-in max() and min() but i started to think of a way to solve it without that.
- So we can input an array, then traverse from the first value of the array.
- Have 2 variables
min_valandmax_valset to the first element of array. - Iterate through each element, comparing with
min_valandmax_val. If the array value is less than min_val, update min_val to array value. Similarly, if array value is greater than max_val update max_val to array value.
Example:
arr = [12, 3, 15, 7, 9]
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
print([min_val, max_val])
Output:
[3,15]
Solution with built-in functions:
This makes use of the python built-in functions max() and min() to get the maximum and minimum values of the array respectively.
arr = [1, 4, 3, 5, 8, 6]
min_val = min(arr)
max_val = max(arr)
print([min_val, max_val])
Output:
[1, 8]
Top comments (0)