ArrayProblem 2 of 36
Find the maximum and minimum element in an array
Problem Statement
Given an array of integers, find the maximum and minimum element in the array.
Example:
- Input:
[3, 5, 4, 1, 9] - Output:
Maximum = 9, Minimum = 1
Approach 1: Linear Search
Intuition
Traverse the entire array while keeping track of the maximum and minimum values seen so far.
Algorithm
- Initialize
maxandminwith the first element - Traverse the array from index 1
- Update
maxif current element is greater - Update
minif current element is smaller
java
public class Solution {
public int[] findMinMax(int[] arr) {
if (arr.length == 0) return new int[]{};
int maxVal = arr[0];
int minVal = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
if (arr[i] < minVal) {
minVal = arr[i];
}
}
return new int[]{maxVal, minVal};
}
}Complexity Analysis
- Time Complexity: O(n) - Single pass, 2(n-1) comparisons
- Space Complexity: O(1) - Only two variables used
Approach 2: Tournament Method (Divide and Conquer)
Intuition
Use divide and conquer to reduce the number of comparisons. Compare elements in pairs.
Algorithm
- If array has one element, it's both min and max
- If array has two elements, compare them
- Divide array into two halves
- Recursively find min-max in both halves
- Compare results from both halves
Complexity Analysis
- Time Complexity: O(n) - Approximately 3n/2 - 2 comparisons
- Space Complexity: O(log n) - Recursion stack depth
Approach 3: Compare in Pairs
Intuition
Process elements in pairs to minimize comparisons.
Algorithm
- Compare elements in pairs
- Compare smaller with current min
- Compare larger with current max
Complexity Analysis
- Time Complexity: O(n) - Exactly 3n/2 - 2 comparisons for even n
- Space Complexity: O(1) - Constant extra space
Key Takeaways
- Pair comparison reduces total comparisons from 2(n-1) to 3n/2-2
- Divide and conquer provides an elegant recursive solution
- For interviews, the linear approach is usually sufficient
- The pair comparison approach is optimal in terms of comparisons