703457. Min and Max in Array
Basic
Min and Max in Array
Slug: find-minimum-and-maximum-element-in-an-array4428
Difficulty: Basic
Topic Tags: Arrays, Data Structures
Company Tags: None
Summary
This problem involves finding the minimum and maximum elements in an array. The key concepts involved are arrays and basic algorithmic thinking.
Detailed Explanation
To solve this problem, we can use a simple iteration through the array to find the minimum and maximum elements. Here's a step-by-step breakdown of the solution:
- Initialize two variables
minandmaxto store the minimum and maximum elements respectively. - Iterate through the array from index 0 to the last element.
- For each element, check if it is less than or equal to the current
min. If it is, updateminwith this new value. - Similarly, for each element, check if it is greater than the current
max. If it is, updatemaxwith this new value. - After iterating through the entire array, the values of
minandmaxwill be the minimum and maximum elements in the array respectively.
The time complexity of this solution is O(n), where n is the size of the array, since we are iterating through the array once. The space complexity is O(1) as we are only using a constant amount of space to store the minimum and maximum elements.
Optimized Solutions
Java
public class Main {
public static void main(String[] args) {
int[] arr = {12, 13, 1, 10, 34, 16};
int min = Integer.MAX_VALUE;
int max = Integer.MIN_VALUE;
for (int i : arr) {
if (i < min) {
min = i;
}
if (i > max) {
max = i;
}
}
System.out.println("Minimum element is " + min);
System.out.println("Maximum element is " + max);
}
}