forked from super30admin/Array-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinAndMax.java
More file actions
34 lines (33 loc) · 981 Bytes
/
Copy pathMinAndMax.java
File metadata and controls
34 lines (33 loc) · 981 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Time Complexity : O(n)
// Space Complexity : O(1)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
/**
* Comparing in pairs
* Edge case: Odd length
* */
class Solution {
public ArrayList<Integer> getMinMax(int[] arr) {
ArrayList<Integer> result = new ArrayList<>();
int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE, i =0;
int n = arr.length;
if(n % 2 == 1){ // for odd length, set min & max as the first element
min = arr[i];
max = arr[i];
i = 1;
}
while (i < n-1){
if(arr[i] > arr[i+1]){
max = Math.max(max, arr[i]);
min = Math.min(min, arr[i+1]);
}else{
max = Math.max(max, arr[i+1]);
min = Math.min(min, arr[i]);
}
i+=2;
}
result.add(min);
result.add(max);
return result;
}
}