-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathB1364_CF.java
More file actions
43 lines (35 loc) · 1.13 KB
/
Copy pathB1364_CF.java
File metadata and controls
43 lines (35 loc) · 1.13 KB
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
35
36
37
38
39
40
41
42
43
import java.util.*;
public class B1364_CF {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int t=scn.nextInt();
while(t-->0){
int n=scn.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=scn.nextInt();
}
ArrayList<Integer>list=new ArrayList<>();
for(int i=0;i<n;i++){
if(i==0 || i==n-1 || (arr[i-1]<arr[i] && arr[i]>arr[i+1]) || (arr[i]<arr[i-1] && arr[i]<arr[i+1])){
list.add(arr[i]);
}
}
System.out.println(list.size());
for(int i:list){
System.out.print(i + " ");
}
System.out.println();
}
}
}
/*
Approach:
Keep only the elements that define the shape of the array.
The first and last elements are always included.
Any element that is a local maximum (peak) or local minimum (valley)
is necessary to preserve direction changes.
All other elements are redundant and can be removed.
Time Complexity: O(n) per test case
Space Complexity: O(n)
*/