Given a permutation $p$ of length $n$, find its subsequence $s_1$, $s_2$, $\ldots$, $s_k$ of length at least $2$ such that:  $|s_1-s_2|+|s_2-s_3|+\ldots+|s_{k-1}-s_k|$ is as big as possible over all subsequences of $p$ with length at least $2$.  Among all such subsequences, choose the one whose length, $k$, is as small as possible. 

If multiple subsequences satisfy these conditions, you are allowed to find any of them.

A sequence $a$ is a subsequence of an array $b$ if $a$ can be obtained from $b$ by deleting some (possibly, zero or all) elements.

A permutation of length $n$ is an array of length $n$ in which every element from $1$ to $n$ occurs exactly once.


-----Input-----

The first line contains an integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. The description of the test cases follows.

The first line of each test case contains an integer $n$ ($2 \le n \le 10^5$) — the length of the permutation $p$.

The second line of each test case contains $n$ integers $p_1$, $p_2$, $\ldots$, $p_{n}$ ($1 \le p_i \le n$, $p_i$ are distinct) — the elements of the permutation $p$.

The sum of $n$ across the test cases doesn't exceed $10^5$.


-----Output-----

For each test case, the first line should contain the length of the found subsequence, $k$. The second line should contain $s_1$, $s_2$, $\ldots$, $s_k$ — its elements.

If multiple subsequences satisfy these conditions, you are allowed to find any of them.


-----Example-----
Input
2
3
3 2 1
4
1 3 4 2

Output
2
3 1 
3
1 4 2 



-----Note-----

In the first test case, there are $4$ subsequences of length at least $2$:  $[3,2]$ which gives us $|3-2|=1$.  $[3,1]$ which gives us $|3-1|=2$.  $[2,1]$ which gives us $|2-1|=1$.  $[3,2,1]$ which gives us $|3-2|+|2-1|=2$. 

So the answer is either $[3,1]$ or $[3,2,1]$. Since we want the subsequence to be as short as possible, the answer is $[3,1]$.

Source: codeforces | Difficulty: EASY
Tags: Amortized analysis

Greedy algorithms


Solutions:
from collections import defaultdict as dd
import math
import sys
input = sys.stdin.readline

def nn():
	return int(input())

def li():
	return list(input())

def mi():
	return map(int, input().split())

def lm():
	return list(map(int, input().split()))
q = nn()
for _ in range(q):
	n = nn()
	per = lm()
	best = [per[0]]
	for i in range(len(per) - 2):
		minper = min(per[i], per[i + 1], per[i + 2])
		maxper = max(per[i], per[i + 1], per[i + 2])
		if minper == per[i + 1] or maxper == per[i + 1]:
			best.append(per[i + 1])
	best.append(per[-1])
	print(len(best))
	print(*best)


from fractions import Fraction
from collections import defaultdict
import math
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')
t = int(input())
for _ in range(t):
	n = int(input())
	l = list([int(x) for x in input().split()])
	res = []
	res.append(l[0])
	for i in range(1, n - 1):
		if l[i] > l[i - 1] and l[i] > l[i + 1]:
			res.append(l[i])
		elif l[i] < l[i - 1] and l[i] < l[i + 1]:
			res.append(l[i])
	res.append(l[n - 1])
	print(len(res))
	print(*res)


import math
import sys
sys.setrecursionlimit(10 ** 4)

def Divisors(n):
	l = []
	i = 1
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				l.append(i)
			else:
				l.append(i)
				l.append(n // i)
		i = i + 1
	return l

def SieveOfEratosthenes(n):
	l = []
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for p in range(2, n + 1):
		if prime[p]:
			l.append(p)
	return l

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(i)
			n = n / i
	if n > 2:
		l.append(n)
	return l

def Factors(n):
	result = []
	for i in range(2, int(math.sqrt(n)) + 1):
		if n % i == 0:
			if i == n / i:
				result.append(i)
			else:
				result.append(i)
				result.append(n // i)
	result.append(1)
	result.append(n)
	return result

def maxSubArraySum(a):
	max_so_far = 0
	max_ending_here = 0
	size = len(a)
	for i in range(0, size):
		max_ending_here = max_ending_here + a[i]
		if max_so_far < max_ending_here:
			max_so_far = max_ending_here
		if max_ending_here < 0:
			max_ending_here = 0
	return max_so_far

def longestsubarray(arr, n, k):
	current_count = 0
	max_count = 0
	for i in range(0, n, 1):
		if arr[i] % k != 0:
			current_count += 1
		else:
			current_count = 0
		max_count = max(current_count, max_count)
	return max_count

def main():
	n = int(input())
	l = list(map(int, input().split()))
	l1 = []
	l1.append(l[0])
	g = 0
	li = 0
	for j in range(1, n):
		if l[j] > l[j - 1]:
			g = 1
		if l[j] < l[j - 1]:
			li = 1
		if l[j] < l[j - 1] and g == 1:
			g = 0
			l1.append(l[j - 1])
			li = 1
		if l[j] > l[j - 1] and li == 1:
			l1.append(l[j - 1])
			g = 1
			li = 0
	l1.append(l[n - 1])
	print(len(l1))
	print(*l1)
t = int(input())
for i in range(0, t):
	main()


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	st = [a[0], a[1]]
	for i in range(2, n):
		if st[-2] > st[-1] and st[-1] > a[i] or (st[-2] < st[-1] and st[-1] < a[i]):
			st.pop()
			st.append(a[i])
		else:
			st.append(a[i])
	print(len(st))
	print(*st)


for _ in ' ' * int(input()):
	n = int(input())
	a = list(map(int, input().split()))
	lst = [a[0]]
	f = 0
	for i in range(1, n - 1):
		if a[i] > a[i - 1] and a[i] > a[i + 1] or (a[i] < a[i - 1] and a[i] < a[i + 1]):
			lst.append(a[i])
	lst.append(a[-1])
	print(len(lst))
	print(*lst)


t = int(input())
for _ in range(t):
	n = int(input())
	P = list(map(int, input().split()))
	ans = [P[0]]
	cur = 0
	for i in range(1, n):
		if cur == 0:
			if P[i - 1] < P[i]:
				cur = 1
			else:
				cur = -1
		elif cur == 1:
			if P[i - 1] < P[i]:
				continue
			else:
				ans.append(P[i - 1])
				cur = -1
		elif P[i - 1] < P[i]:
			ans.append(P[i - 1])
			cur = 1
		else:
			continue
	else:
		ans.append(P[-1])
	print(len(ans))
	print(*ans)


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
import sys
from bisect import *
from math import floor, sqrt, ceil, factorial as F, gcd, pi, log
from itertools import chain, combinations, permutations, accumulate
from collections import Counter, defaultdict, OrderedDict, deque
from functools import cmp_to_key, reduce
INT_MAX = sys.maxsize
INT_MIN = -sys.maxsize - 1
mod = 1000000007
ch = 'abcdefghijklmnopqrstuvwxyz'
lcm = lambda a, b: a * b // gcd(a, b)
setbit = lambda x: bin(x)[2:].count('1')
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def solve():
	T = int(sys.stdin.readline())
	for _ in range(T):
		n = int(sys.stdin.readline())
		a = list(map(int, sys.stdin.readline().split()))
		ans = set()
		for i in range(n):
			if not (i - 1 >= 0 and a[i - 1] > a[i] or (i + 1 < n and a[i + 1] > a[i])):
				ans.add(a[i])
		for i in range(n):
			if not (i - 1 >= 0 and a[i - 1] < a[i] or (i + 1 < n and a[i + 1] < a[i])):
				ans.add(a[i])
		res = []
		for i in range(n):
			if a[i] in ans:
				res.append(a[i])
		print(len(res))
		print(*res)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
solve()


from sys import stdin, stdout

def input():
	return stdin.readline()
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	l = []
	l.append(a[0])
	(s, g) = (-1, -1)
	for i in range(1, n):
		if a[i] > a[i - 1]:
			if s == 1:
				l.append(a[i - 1])
			g = 1
			s = 0
		elif a[i] < a[i - 1]:
			if g == 1:
				l.append(a[i - 1])
			s = 1
			g = 0
	if a[-1] not in l:
		l.append(a[-1])
	print(len(l))
	print(*l)


import queue
testcases = int(input())
for i in range(testcases):
	n = int(input())
	l = list(map(int, input().strip().split(' ')))
	q = queue.Queue()
	result = []
	result.append(l[0])
	for i in range(1, n - 1):
		if l[i - 1] < l[i] < l[i + 1] or l[i - 1] > l[i] > l[i + 1]:
			pass
		else:
			result.append(l[i])
	result.append(l[-1])
	print(len(result))
	for i in result:
		print(i, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = [l[0]]
	last = l[0]
	i = 1
	while i < n:
		if l[i] >= last:
			j = i + 1
			last = l[i]
			while j < n and l[j] >= last:
				last = l[j]
				j += 1
			if last != ans[-1]:
				ans.append(last)
			i = j
			continue
		if l[i] < last:
			j = i + 1
			last = l[i]
			while j < n and l[j] < last:
				last = l[j]
				j += 1
			if last != ans[-1]:
				ans.append(last)
			i = j
	print(len(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	max = -1
	l = []
	l.append(a[0])
	for i in range(1, n - 1):
		if a[i] < a[i - 1] and a[i] < a[i + 1] or (a[i] > a[i - 1] and a[i] > a[i + 1]):
			l.append(a[i])
	l.append(a[n - 1])
	print(len(l))
	print(*l)


import sys
import os
import heapq
import math
try:
	path = './file/input.txt'
	if os.path.exists(path):
		sys.stdin = open(path, 'r')
except:
	pass
t = int(input())

def printd(value):
	pass

def case():
	n = int(input())
	p = list(map(int, input().split(' ')))
	first = p[0]
	result = [first]
	for index in range(2, n):
		value = p[index]
		last = p[index - 1]
		if not (first > last and last > value or (first < last and last < value)):
			result.append(last)
			first = last
	result.append(p[n - 1])
	print(len(result))
	print(' '.join((str(i) for i in result)))
for _ in range(t):
	case()


t = int(input())
for test in range(0, t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [a[0]]
	for i in range(1, n - 1):
		if a[i] > a[i - 1] and a[i] > a[i + 1]:
			ans.append(a[i])
		if a[i] < a[i - 1] and a[i] < a[i + 1]:
			ans.append(a[i])
	ans.append(a[n - 1])
	print(len(ans))
	print(*ans, sep=' ')


for i in range(int(input())):
	n = int(input())
	a = [int(s) for s in input().split()]
	b = [a[0]]
	for j in range(1, n - 1):
		if a[j - 1] < a[j] > a[j + 1] or a[j - 1] > a[j] < a[j + 1]:
			b.append(a[j])
	print(len(b) + 1)
	print(' '.join([str(x) for x in b]), a[-1])


def help():
	n = int(input())
	arr = list(map(int, input().split(' ')))
	peak = [False] * n
	down = [False] * n
	for i in range(n):
		if i == 0:
			if arr[0] < arr[1]:
				down[0] = True
			if arr[0] > arr[1]:
				peak[i] = True
		elif i == n - 1:
			if arr[n - 1] < arr[n - 2]:
				down[i] = True
			if arr[n - 1] > arr[n - 2]:
				peak[i] = True
		elif arr[i - 1] < arr[i] and arr[i] > arr[i + 1]:
			peak[i] = True
		elif arr[i - 1] > arr[i] and arr[i] < arr[i + 1]:
			down[i] = True
	series = []
	for i in range(n):
		if peak[i] == True or down[i] == True:
			series.append(i)
	ans = 0
	for i in range(len(series) - 1):
		ans += abs(series[i] - series[i + 1])
	print(len(series))
	for i in range(len(series)):
		print(arr[series[i]], end=' ')
	print()
for _ in range(int(input())):
	help()


def tran(arr):
	sub = []
	for i in range(len(arr) - 1):
		sub.append(arr[i + 1] - arr[i])
	c = 0
	anss = [arr[c]]
	for i in range(len(sub) - 1):
		if sub[i + 1] * sub[i] < 0:
			c = c + 1
			anss.append(arr[c])
		else:
			c = c + 1
	if anss[-1] == arr[-1]:
		return [len(anss), anss]
	else:
		anss.append(arr[-1])
		return [len(anss), anss]
t = int(input())
ans = []
for i in range(t):
	n = int(input())
	arr = list(map(int, input().rstrip().split()))
	r = tran(arr)
	ans.append(r)
for i in ans:
	print(i[0])
	print(*i[1])


import math, sys
from sys import stdin, stdout
from collections import Counter, defaultdict, deque
input = stdin.readline
I = lambda : int(input())
li = lambda : list(map(int, input().split()))

def solve():
	n = I()
	a = li()
	ans = [-1] * n
	key = a[0]
	pink = [a[0]]
	for i in range(1, n - 1):
		if a[i] > a[i - 1] and a[i] > a[i + 1]:
			pink.append(a[i])
		elif a[i] < a[i - 1] and a[i] < a[i + 1]:
			pink.append(a[i])
	pink.append(a[-1])
	print(len(pink))
	print(*pink)
for _ in range(I()):
	solve()


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	l = []
	c = 0
	for i in range(n - 1):
		if i == 0:
			if p[i + 1] > p[i]:
				f = True
			else:
				f = False
			c += 1
			l.append(p[0])
			continue
		if p[i + 1] < p[i] and f:
			c += 1
			l.append(p[i])
			f = not f
		elif p[i + 1] > p[i] and (not f):
			c += 1
			l.append(p[i])
			f = not f
	l.append(p[-1])
	print(c + 1)
	print(*l)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	l = []
	l.append(a[0])
	(lo, hi) = (0, 1)
	temp = a[0]
	while hi < n:
		while hi < n and temp < a[hi]:
			temp = a[hi]
			hi += 1
		if l[-1] != a[hi - 1]:
			l.append(a[hi - 1])
		while hi < n and temp > a[hi]:
			temp = a[hi]
			hi += 1
		if l[-1] != a[hi - 1]:
			l.append(a[hi - 1])
	print(len(l))
	print(*l)


for _ in range(int(input())):
	input()
	ans = []
	for x in map(int, input().split()):
		if len(ans) >= 2 and (ans[-2] < ans[-1]) == (ans[-1] < x):
			ans.pop()
		ans.append(x)
	print(len(ans))
	print(*ans)


t = int(input())
from heapq import heappush as pu
from heapq import heappop as po
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	an = []
	p = 0 if a[1] > a[0] else 1
	i = 1
	while i < n:
		if p:
			if a[i] > a[i - 1]:
				i += 1
			else:
				an.append(a[i - 1])
				p = 0
				i += 1
		elif a[i] < a[i - 1]:
			i += 1
		else:
			an.append(a[i - 1])
			p = 1
			i += 1
	an.append(a[-1])
	print(len(an))
	print(*an)


for case in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	new_a = [a[0]]
	for i in range(1, n - 1):
		if a[i] >= a[i - 1] and a[i] > a[i + 1] or (a[i] <= a[i - 1] and a[i] < a[i + 1]):
			new_a.append(a[i])
	new_a.append(a[-1])
	print(len(new_a))
	print(*new_a)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = []
	for i in range(n):
		if i == 0 or i == n - 1 or (arr[i - 1] < arr[i]) != (arr[i] < arr[i + 1]):
			ans.append(arr[i])
	print(len(ans))
	print(*ans)


t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	res = [arr[0]]
	for i in range(1, n - 1):
		if arr[i] > arr[i + 1] and arr[i] > arr[i - 1]:
			res.append(arr[i])
		if arr[i] < arr[i + 1] and arr[i] < arr[i - 1]:
			res.append(arr[i])
	res.append(arr[n - 1])
	ans = list(map(str, res))
	print(len(ans))
	print(' '.join(ans))


a = int(input())
for i in range(a):
	n = int(input())
	l = list(map(int, input().split()))
	s = 2
	bb = []
	bb.append(l[0])
	for j in range(1, n - 1):
		if not (l[j - 1] >= l[j] and l[j] >= l[j + 1] or (l[j - 1] <= l[j] and l[j] <= l[j + 1])):
			bb.append(l[j])
	bb.append(l[-1])
	print(len(bb))
	print(*bb)


import math
for i in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	out = [str(a[0])]
	if a[1] > a[0]:
		u = True
	else:
		u = False
	for i in range(1, n - 1):
		if a[i + 1] > a[i]:
			u1 = True
		else:
			u1 = False
		if u ^ u1:
			out.append(str(a[i]))
		u = u1
	print(len(out) + 1)
	print(' '.join(out), a[-1])


import sys
input = sys.stdin.readline
from math import ceil, floor, factorial

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if a == 0:
		return b
	return gcd(b % a, a)

def nCr(n, k):
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def upper_bound(a, x, lo=0):
	hi = len(a)
	while lo < hi:
		mid = (lo + hi) // 2
		if a[mid] < x:
			lo = mid + 1
		else:
			hi = mid
	return lo

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime
MAXN = int(10000000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i

def factoriazation(x):
	ret = {}
	while x != 1:
		ret[spf[x]] = ret.get(spf[x], 0) + 1
		x = x // spf[x]
	return ret

def int_array():
	return list(map(int, input().strip().split()))

def str_array():
	return input().strip().split()
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
for _ in range(int(input())):
	n = int(input())
	a = int_array()
	if a[1] > a[0]:
		incs = 1
	else:
		incs = 0
	start = a[0]
	prev = a[1]
	ans = [start, prev]
	for i in range(2, n):
		if a[i] > prev:
			if incs == 1:
				ans.pop()
				prev = a[i]
				ans.append(prev)
			else:
				incs = 1
				start = prev
				prev = a[i]
				ans.append(prev)
		elif incs == 1:
			incs = 0
			start = prev
			prev = a[i]
			ans.append(prev)
		else:
			ans.pop()
			prev = a[i]
			ans.append(prev)
	print(len(ans))
	print(*ans)


for i in range(int(input())):
	n = int(input())
	arr = [int(i) for i in input().split()]
	stk = arr[0:2]
	fixed = 0
	for i in arr[2:]:
		if (stk[fixed] - stk[-1]) * (stk[-1] - i) > 0:
			stk.pop()
			stk.append(i)
		else:
			stk.append(i)
			fixed += 1
	print(len(stk))
	print(*stk)


t = int(input())
for j in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	result = []
	for i in range(1, n - 1):
		if p[i] > p[i - 1] and p[i] > p[i + 1] or (p[i] < p[i - 1] and p[i] < p[i + 1]):
			result.append(p[i])
	final = [p[0]]
	final.extend(result)
	final.append(p[-1])
	print(len(final))
	print(*final)


import sys
input = sys.stdin.readline

def solve():
	n = int(input())
	arr = [int(x) for x in input().split()]
	ans = [arr[0]]
	for i in range(1, n - 1):
		if not (arr[i - 1] < arr[i] < arr[i + 1] or arr[i - 1] > arr[i] > arr[i + 1]):
			ans.append(arr[i])
	ans.append(arr[-1])
	print(len(ans))
	print(*ans)
tt = int(input())
for test in range(tt):
	solve()


for _ in range(int(input())):
	N = int(input())
	List = [int(x) for x in input().split()]
	Ans = [List[0]]
	if len(List) == 2:
		print(2)
		print(*List)
		continue
	for i in range(1, N - 1):
		if List[i - 1] < List[i] < List[i + 1]:
			continue
		elif List[i - 1] > List[i] > List[i + 1]:
			continue
		else:
			Ans.append(List[i])
	Ans.append(List[-1])
	print(len(Ans))
	print(*Ans)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	p = [l[0]]
	for i in range(1, n - 1):
		if l[i] > l[i - 1] and l[i] > l[i + 1]:
			p.append(l[i])
		if l[i] < l[i - 1] and l[i] < l[i + 1]:
			p.append(l[i])
	p.append(l[-1])
	s = 0
	t = len(p)
	print(t)
	print(*p)


t = int(input())
for w in range(t):
	n = int(input())
	l = [int(i) for i in input().split()]
	c = 1
	l1 = [l[0]]
	for i in range(1, n - 1):
		if l[i] > l[i - 1] and l[i] > l[i + 1] or (l[i] < l[i - 1] and l[i] < l[i + 1]):
			c += 1
			l1 += [l[i]]
	c += 1
	l1 += [l[n - 1]]
	print(c)
	print(*l1)


t = int(input())
for tt in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	v = [a[0], a[1]]
	for i in range(2, n):
		if v[-2] > v[-1] and v[-1] > a[i] or (v[-2] < v[-1] and v[-1] < a[i]):
			v.pop()
		v.append(a[i])
	print(len(v))
	print(' '.join(map(str, v)))


from collections import deque
import sys

def inp():
	return sys.stdin.readline().strip()
for _ in range(int(inp())):
	n = int(inp())
	a = list(map(int, inp().split()))
	vis = [False] * n
	prev = a[0]
	ans = [a[0]]
	for i in range(n):
		if i + 1 < n and abs(a[i] - prev) + abs(a[i] - a[i + 1]) == abs(a[i + 1] - prev):
			vis[i] = True
			continue
		ans.append(a[i])
		prev = a[i]
	print(len(ans))
	print(*ans)


t = int(input())
for q in range(t):
	n = int(input())
	entrada = list(map(int, input().split(' ')))
	soma = 0
	vet = [True] * n
	for k in range(n - 1):
		soma += abs(entrada[k] - entrada[k + 1])
	adjEsq = 1
	elementos = n
	for i in range(n - 1):
		if i != 0:
			if abs(entrada[i] - entrada[i + 1]) + abs(entrada[i] - entrada[i - adjEsq]) <= abs(entrada[i - adjEsq] - entrada[i + 1]):
				elementos -= 1
				adjEsq += 1
				vet[i] = False
			else:
				adjEsq = 1
	print(elementos)
	for j in range(n):
		if vet[j] != False:
			print(entrada[j], end=' ')
	print()


I = lambda : map(int, input().split())
for _ in [0] * int(input()):
	n = int(input())
	a = list(I())
	x = a[0]
	b = [x]
	gg = 1
	ff = int(a[1] > a[0])
	for j in range(1, n):
		i = a[j]
		if ff == 1 and i < x or (ff == 0 and i > x):
			b.append(x)
			gg = gg + 1
			ff = 1 - ff
		x = i
	print(gg + 1)
	print(*b + [i])


for _ in range(int(input())):
	x = int(input())
	(*li,) = map(int, input().split())
	li1 = [li[0]]
	for i in range(1, x - 1):
		if li[i] > li[i - 1] and li[i] > li[i + 1]:
			li1.append(li[i])
		elif li[i] < li[i - 1] and li[i] < li[i + 1]:
			li1.append(li[i])
	li1.append(li[-1])
	print(len(li1))
	print(*li1)


from io import BytesIO, IOBase
from math import sqrt
import sys, os
inpl = lambda : list(map(int, input().split()))
inpm = lambda : map(int, input().split())
inpi = lambda : int(input())
inp = lambda : input()
(rev, ra, l) = (reversed, range, len)
P = print
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')

def B(n):
	return bin(n).replace('0b', '')

def factors(n):
	arr = []
	for i in ra(2, int(sqrt(n)) + 1):
		if n % i == 0:
			arr.append(i)
			if i * i != n:
				arr.append(int(n / i))
	return arr

def dfs(arr, n):
	pairs = [[i + 1] for i in ra(n)]
	vis = [0] * (n + 1)
	for i in ra(l(arr)):
		pairs[arr[i][0] - 1].append(arr[i][1])
	pairs[arr[i][1] - 1].append(arr[i][0])
	comp = []
	for i in ra(n):
		stack = [pairs[i]]
		temp = []
		if vis[stack[-1][0]] == 0:
			while len(stack) > 0:
				if vis[stack[-1][0]] == 0:
					temp.append(stack[-1][0])
					vis[stack[-1][0]] = 1
					s = stack.pop()
					for j in s[1:]:
						if vis[j] == 0:
							stack.append(pairs[j - 1])
				else:
					stack.pop()
			comp.append(temp)
	return comp
from bisect import bisect_left as bl
from bisect import bisect_right as br
import sys, operator, math, operator
import random
tc = inpi()
while tc:
	tc -= 1
	n = inpi()
	li = inpl()
	ans = [li[0]]
	i = 1
	idx = 0
	while i < n - 1:
		a = abs(li[i - 1] - li[i + 1])
		b = abs(li[i] - li[i - 1]) + abs(li[i + 1] - li[i])
		if a >= b:
			pass
		else:
			ans.append(li[i])
		i += 1
	if idx != n - 1:
		ans.append(li[-1])
	P(l(ans))
	P(*ans)


for _ in range(int(input())):
	n = int(input())
	p = tuple(map(int, input().split()))
	ans = [p[i] for i in range(n) if i in (0, n - 1) or p[i] != sorted(p[i - 1:i + 2])[1]]
	print(len(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	p = [int(x) for x in input().split()]
	subseq = [p[0]]
	for i in range(1, n - 1):
		if p[i - 1] <= p[i] and p[i] > p[i + 1]:
			subseq.append(p[i])
		elif p[i - 1] >= p[i] and p[i] < p[i + 1]:
			subseq.append(p[i])
	subseq.append(p[-1])
	print(len(subseq))
	print(' '.join([str(x) for x in subseq]))


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	seq1 = 0
	seq2 = 0
	final = []
	final.append(l[0])
	for i in range(1, n - 1):
		if (l[i - 1] < l[i]) != (l[i] < l[i + 1]):
			final.append(l[i])
	final.append(l[-1])
	print(len(final))
	print(*final)


def solve():
	n = int(input())
	lst = list(map(int, input().split()))
	k = 1
	elems = [lst[0]]
	for i in range(1, n - 1):
		if lst[i - 1] > lst[i] < lst[i + 1] or lst[i - 1] < lst[i] > lst[i + 1]:
			k += 1
			elems.append(lst[i])
	elems.append(lst[-1])
	k += 1
	print(k)
	print(*elems)
for t in range(int(input())):
	solve()


t = int(input())
while t:
	n = int(input())
	a = [int(i) for i in input().split()]
	pre = [a[0]]
	for ele in a:
		if pre[-1] != ele:
			pre.append(ele)
	a = pre
	ans = []
	ans.append(a[0])
	count = 1
	n = len(a)
	for i in range(1, n - 1):
		if a[i] == ans[-1]:
			continue
		if a[i - 1] <= a[i] >= a[i + 1] or a[i - 1] >= a[i] <= a[i + 1]:
			ans.append(a[i])
			count += 1
	if ans[-1] != a[-1]:
		ans.append(a[-1])
		count += 1
	print(count)
	for ele in ans:
		print(ele, end=' ')
	print()
	t -= 1


for _ in range(int(input())):
	n = int(input())
	s = list(map(int, input().split()))
	ans = []
	ans.append(s[0])
	for i in range(1, len(s) - 1):
		if s[i] > ans[-1] and s[i] < s[i + 1]:
			n = n
		elif s[i] < ans[-1] and s[i] > s[i + 1]:
			n = n
		else:
			ans.append(s[i])
	ans.append(s[-1])
	print(len(ans))
	print(*ans)


import io
import os
from collections import Counter, defaultdict, deque

def solve(N, P):
	ans = []
	for (x, y, z) in zip(P, P[1:], P[2:]):
		if x < y and y > z or (x > y and y < z):
			ans.append(y)
	ans = [P[0]] + ans + [P[-1]]
	return str(len(ans)) + '\n' + ' '.join(map(str, ans))
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
	(N,) = [int(x) for x in input().split()]
	P = [int(x) for x in input().split()]
	ans = solve(N, P)
	print(ans)


t = int(input())
while t:
	t += -1
	n = int(input())
	l = list(map(int, input().split()))
	ans = [l[0]]
	ch = 0
	for i in range(1, n):
		if l[i] < l[i - 1]:
			if ch:
				ch = 0
				ans.append(l[i - 1])
		elif ch == 0:
			ch = 1
			if i != 1:
				ans.append(l[i - 1])
	ans.append(l[n - 1])
	print(len(ans))
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	s = [p[0], p[1]]
	for i in range(2, n):
		if p[i] > s[-1] and s[-1] > s[-2]:
			s.pop()
		elif p[i] < s[-1] and s[-1] < s[-2]:
			s.pop()
		s.append(p[i])
	print(len(s))
	print(*s)


def doing():
	n = int(input())
	a = list(map(int, input().split()))
	b = [a[0]]
	for i in range(1, n - 1):
		if a[i - 1] <= a[i] <= a[i + 1] or a[i - 1] >= a[i] >= a[i + 1]:
			continue
		else:
			b.append(a[i])
	b.append(a[n - 1])
	print(len(b))
	print(' '.join([str(it) for it in b]))
T = int(input())
for i in range(T):
	doing()


import os
import sys
debug = True
if debug and os.path.exists('input.in'):
	input = open('input.in', 'r').readline
else:
	debug = False
	input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())
test_count = int(input())
for t in range(test_count):
	if debug:
		print('Test Case #', t + 1)
	n = inp()
	a = inlt()
	dir = 0
	last = a[0]
	ans = list()
	ans.append(last)
	for i in range(1, n):
		curr = a[i]
		if curr > last:
			if dir == 0 or dir == 1:
				dir = 1
			else:
				ans.append(last)
				dir = 1
		elif dir == 0 or dir == -1:
			dir = -1
		else:
			ans.append(last)
			dir = -1
		last = curr
	ans.append(last)
	print(len(ans))
	print(' '.join(map(str, ans)))


def run():
	t = int(input())
	for i in range(t):
		n = int(input())
		num = [int(j) for j in input().split()]
		ans = [num[0]]
		aux = num[1]
		decre = aux > num[0]
		for i in range(2, n):
			if num[i] > aux:
				if not decre:
					ans.append(aux)
					decre = not decre
			elif decre:
				ans.append(aux)
				decre = not decre
			aux = num[i]
		ans.append(aux)
		print(len(ans))
		print(*ans)
run()


T = int(input())
for _ in range(T):
	n = int(input())
	p = list(map(int, input().strip().split()))
	res = [p[0]]
	diff = None
	for i in range(1, n):
		curr_diff = p[i] - p[i - 1]
		if diff == None:
			diff = curr_diff
			res.append(p[i])
		elif diff > 0 and curr_diff > 0:
			res[-1] = p[i]
		elif diff < 0 and curr_diff < 0:
			res[-1] = p[i]
		else:
			res.append(p[i])
			diff = curr_diff
	print(len(res))
	print(' '.join(map(str, res)))


for _ in range(int(input())):
	n = int(input())
	u = list(map(int, input().split()))
	b = []
	b.append(u[0])
	for i in range(1, n - 1):
		if u[i] > u[i - 1] and u[i] > u[i + 1] or (u[i] < u[i - 1] and u[i] < u[i + 1]):
			b.append(u[i])
	b.append(u[-1])
	print(len(b))
	print(' '.join(map(str, b)))


from sys import stdin, stdout
t = int(stdin.readline().strip())
for _ in range(t):
	n = int(stdin.readline().strip())
	p = list(map(int, stdin.readline().strip().split(' ')))
	ans = [p[0]]
	for i in range(1, len(p) - 1):
		if (p[i] - ans[-1]) * (p[i + 1] - p[i]) < 0:
			ans.append(p[i])
	if p[-1] != ans[-1]:
		ans.append(p[-1])
	stdout.write(str(len(ans)) + '\n')
	stdout.write(' '.join(list(map(str, ans))).strip() + '\n')


import sys
sys.setrecursionlimit(10 ** 6)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.readline())

def MI():
	return map(int, sys.stdin.readline().split())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def SI():
	return sys.stdin.readline()[:-1]

def solve():
	res = [aa[0]]
	for i in range(1, n - 1):
		if aa[i - 1] < aa[i] > aa[i + 1] or aa[i - 1] > aa[i] < aa[i + 1]:
			res.append(aa[i])
	res.append(aa[-1])
	return res
for _ in range(II()):
	n = II()
	aa = LI()
	ans = solve()
	print(len(ans))
	print(*ans)


def solve_test_case(t):
	n = int(input())
	p = parse_array(int)
	res = [p[0]]
	for i in range(1, n - 1):
		if p[i] >= p[i - 1] and p[i + 1] >= p[i]:
			pass
		elif p[i] <= p[i - 1] and p[i + 1] <= p[i]:
			pass
		else:
			res.append(p[i])
	if n > 1:
		res.append(p[-1])
	print(len(res))
	print(' '.join(list(map(str, res))))

def parse_array(f):
	return list(map(f, input().split()))

def solve():
	T = int(input())
	for t in range(T):
		solve_test_case(t)
solve()


import sys
import math as mt
input = sys.stdin.buffer.readline
t = int(input())
for __ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	ans = []
	ans.append(l[0])
	for i in range(1, n - 1):
		if l[i - 1] < l[i] and l[i] < l[i + 1]:
			continue
		if l[i - 1] > l[i] and l[i] > l[i + 1]:
			continue
		ans.append(l[i])
	if len(l) > 1:
		ans.append(l[-1])
	print(len(ans))
	print(*ans)


from sys import stdin, stdout
int_in = lambda : int(stdin.readline())
arr_in = lambda : [int(x) for x in stdin.readline().split()]
mat_in = lambda rows: [arr_in() for y in range(rows)]
str_in = lambda : stdin.readline().strip()
out = lambda o: stdout.write('{}\n'.format(o))
arr_out = lambda o: out(' '.join(map(str, o)))
bool_out = lambda o: out('YES' if o else 'NO')
tests = lambda : range(1, int_in() + 1)
case_out = lambda i, o: out('Case #{}: {}'.format(i, o))

def solve(n, p):
	result = [p[0]]
	going_down = p[0] - p[1] > 0
	for i in range(1, n):
		if going_down and p[i - 1] - p[i] < 0:
			going_down = False
			result.append(p[i - 1])
		elif not going_down and p[i - 1] - p[i] > 0:
			going_down = True
			result.append(p[i - 1])
	result.append(p[-1])
	return result
for i in tests():
	n = int_in()
	p = arr_in()
	result = solve(n, p)
	out(len(result))
	arr_out(result)


def main():
	t = int(input())
	for i in range(t):
		solve()

def solve():
	n = int(input())
	arr = list(map(int, input().split(' ')))
	if n == 2:
		print(n)
		print(*arr)
		return
	prev = arr.pop(0)
	numbers = [prev]
	amount = 1
	while len(arr) > 1:
		current = arr.pop(0)
		if current > numbers[amount - 1] and current > arr[0] or (current < numbers[amount - 1] and current < arr[0]):
			amount += 1
			prev = current
			numbers.append(current)
	numbers.append(arr.pop(0))
	amount += 1
	print(amount)
	print(*numbers)
main()


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	i = 1
	indices = [0]
	while i < len(arr):
		while i < len(arr) and arr[i] <= arr[i - 1]:
			i += 1
		if i != 1:
			indices.append(i - 1)
		if i == len(arr):
			break
		while i < len(arr) and arr[i] >= arr[i - 1]:
			i += 1
		if i != 1:
			indices.append(i - 1)
	if i != len(arr):
		indices.append(len(arr))
	ans = 0
	print(len(indices))
	for i in range(len(indices)):
		print(arr[indices[i]], end=' ')
	print()


import sys
input = sys.stdin.buffer.readline

def isIncreasing(a, b):
	return a < b
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(x) for x in input().split()]
	resStack = []
	for x in arr:
		if len(resStack) == 0 or len(resStack) == 1:
			resStack.append(x)
		else:
			if isIncreasing(resStack[-2], resStack[-1]) == isIncreasing(resStack[-1], x):
				resStack.pop()
			resStack.append(x)
	print(len(resStack))
	print(' '.join([str(x) for x in resStack]))


from sys import stdin, stdout, setrecursionlimit
from collections import deque, defaultdict
import math
rl = lambda : stdin.readline()
rll = lambda : stdin.readline().split()
rli = lambda : map(int, stdin.readline().split())
rlf = lambda : map(float, stdin.readline().split())
(INF, NINF) = (float('inf'), float('-inf'))

def main():
	T = int(rl())
	locmin = lambda x, L: L[x - 1] > L[x] and L[x] < L[x + 1]
	locmax = lambda x, L: L[x - 1] < L[x] and L[x] > L[x + 1]
	for _ in range(T):
		n = int(rl())
		P = list(rli())
		ans = []
		for (i, num) in enumerate(P):
			if i == 0 or i == n - 1:
				ans.append(num)
			elif locmin(i, P) or locmax(i, P):
				ans.append(num)
		print(len(ans))
		print(' '.join((str(x) for x in ans)))
	stdout.close()
main()


t = int(input())
for i in range(0, t):
	n = int(input())
	l = list(map(int, input().split()))
	m = [l[0]]
	for i in range(1, len(l) - 1):
		if (l[i - 1] < l[i]) == (l[i] > l[i + 1]):
			m.append(l[i])
	m.append(l[-1])
	print(len(m))
	print(*m)


import math
for _ in range(int(input())):
	n = int(input())
	array = list(map(int, input().split()))
	new_array = [array[0], array[1]]
	Increasing = False
	if array[1] >= array[0]:
		Increasing = True
	for i in array[2:]:
		if Increasing:
			if i > new_array[-1]:
				new_array[-1] = i
			elif i < new_array[-1]:
				new_array.append(i)
				Increasing = False
		elif i < new_array[-1]:
			new_array[-1] = i
		elif i > new_array[-1]:
			new_array.append(i)
			Increasing = True
	print(len(new_array))
	print(*new_array)


import getopt
import sys
import math
onlyCase = -1
verbose = False
try:
	(opts, args) = getopt.getopt(sys.argv[1:], 'vc:', ['case='])
except getopt.GetoptError as err:
	print(str(err))
	sys.exit(2)
for (o, a) in opts:
	if o in ('-c', '--case'):
		onlyCase = int(a)
	elif o == '-v':
		verbose = True
	else:
		sys.exit()
ncases = int(input())
for c in range(1, ncases + 1):
	_ = input()
	A = [int(x) for x in input().split()]
	if onlyCase != -1 and onlyCase != c:
		continue
	N = []
	N.append(A[0])
	for i in range(1, len(A) - 1):
		if N[-1] < A[i] and A[i] < A[i + 1]:
			continue
		if N[-1] > A[i] and A[i] > A[i + 1]:
			continue
		N.append(A[i])
	N.append(A[-1])
	print('%d\n%s' % (len(N), ' '.join(map(str, N))))


t = int(input())
while t > 0:
	n = int(input())
	l = list(map(int, input().split()))
	ans = [0, abs(l[1] - l[0])]
	a = [l[0]]
	for i in range(2, n):
		if ans[i - 1] + abs(l[i] - l[i - 1]) > ans[i - 2] + abs(l[i] - l[i - 2]):
			ans.append(ans[i - 1] + abs(l[i] - l[i - 1]))
			a.append(l[i - 1])
		else:
			ans.append(ans[i - 2] + abs(l[i] - l[i - 2]))
	a.append(l[-1])
	print(len(a))
	for i in a:
		print(i, end=' ')
	print()
	t -= 1


t = int(input())
while t != 0:
	t -= 1
	n = int(input())
	lt = [int(x) for x in input().split()]
	p = []
	p.append(lt[0])
	for i in range(1, n - 1):
		if (lt[i] - lt[i - 1]) * (lt[i] - lt[i + 1]) >= 0:
			if lt[i] != p[-1]:
				p.append(lt[i])
	if lt[-1] != p[-1]:
		p.append(lt[-1])
	print(len(p))
	print(*p)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	l = []
	start = 0
	end = 0
	for j in range(len(a) - 1):
		l.append(a[j + 1] - a[j])
	q = []
	io = [a[0]]
	minus = 0
	add = 0
	for j in range(len(l)):
		if l[j] < 0:
			if add != 0:
				q.append(add)
				io.append(a[j])
			add = 0
			minus = minus + l[j]
		if l[j] > 0:
			if minus != 0:
				q.append(minus)
				io.append(a[j])
			minus = 0
			add = add + l[j]
	if minus != 0:
		q.append(minus)
	if add != 0:
		q.append(add)
	if len(q) == 0:
		print(2)
		print(a[0], a[1])
	else:
		io.append(a[-1])
		print(len(io))
		print(*io)


for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	ans = []
	maxi = max(ar)
	mini = min(ar)
	to_beat = maxi - mini
	if ar[1] > ar[0]:
		direction = 'd'
	else:
		direction = 'u'
	ans.append(ar[0])
	for i in range(1, n):
		if direction == 'u':
			if ar[i] > ans[-1]:
				ans[-1] = ar[i]
			elif ar[i] < ans[-1]:
				ans.append(ar[i])
				direction = 'd'
		elif ar[i] < ans[-1]:
			ans[-1] = ar[i]
		elif ar[i] > ans[-1]:
			ans.append(ar[i])
			direction = 'u'
	print(len(ans))
	print(*ans)


import sys
input = lambda : sys.stdin.readline().split('\n')[0]
t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	l = list(map(int, input().split(' ')))
	ans = [l[0]]
	last = l[0]
	for i in range(1, n - 1):
		if l[i] > last and l[i + 1] > l[i] or (l[i] < last and l[i + 1] < l[i]):
			continue
		else:
			ans.append(l[i])
			last = l[i]
	ans.append(l[-1])
	print(len(ans))
	print(*ans, sep=' ')


n = int(input())
a = []
while n:
	x = int(input())
	l = [int(i) for i in input().split()]
	ans = []
	for i in range(x):
		try:
			if i == 0 or i == x - 1 or (l[i - 1] < l[i]) != (l[i] < l[i + 1]):
				ans.append(l[i])
		except:
			pass
	a.append(ans)
	n = n - 1
for i in a:
	print(len(i))
	for j in i:
		print(j, end=' ')
	print()


from math import sqrt
tll = int(input())
while tll > 0:
	tll -= 1
	n = int(input())
	l = list(map(int, input().split()))
	ans = []
	for i in range(1, n - 1):
		if not abs(l[i] - l[i - 1]) + abs(l[i + 1] - l[i]) <= abs(l[i + 1] - l[i - 1]):
			ans.append(l[i])
	some = len(ans)
	ans.insert(0, l[0])
	ans.insert(some + 1, l[-1])
	print(some + 2)
	for i in ans:
		print(i, end=' ', sep=' ')
	print()


from queue import LifoQueue

def print_sol(c, sol):
	print('Case #{}: {}'.format(c, sol))

def rd_int():
	return int(input())

def rd_str():
	return input()

def rd_str_lst():
	return input().split(' ')

def sp_str_lst():
	return list(input())

def rd_int_lst():
	return [int(i) for i in rd_str_lst()]

def sp_int_lst():
	return [int(i) for i in sp_str_lst()]

def dfs(g, i, v):
	v[i] = True
	for j in g[i]:
		if not v[j]:
			dfs(g, j, v)
	print(i)

def dfs_iter(g, i, n):
	v = [False] * n
	stack = LifoQueue()
	stack.put(i)
	while stack.not_empty:
		u = stack.get()
		v[u] = True
		print(u)
		for i in g[u]:
			if not v[i]:
				stack.put(i)

def main():
	t = rd_int()
	for c in range(1, t + 1):
		n = rd_int()
		p = rd_int_lst()
		inc = True if p[1] > p[0] else False
		s = [0] * n
		s[0] = p[0]
		k = 1
		for i in range(2, n):
			if inc:
				if p[i] > p[i - 1]:
					continue
				else:
					inc = False
					s[k] = p[i - 1]
					k += 1
			elif p[i] < p[i - 1]:
				continue
			else:
				inc = True
				s[k] = p[i - 1]
				k += 1
		s[k] = p[n - 1]
		k += 1
		print(k)
		print(*s[:k])
main()


import sys
input = sys.stdin.buffer.readline
t = int(input())
ans = []
for _ in range(t):
	n = int(input())
	(*p,) = map(int, input().split())
	if n == 2:
		ans.append('2')
		ans.append(' '.join(map(str, p)))
		continue
	pp = [y for (x, y, z) in zip(p, p[1:], p[2:]) if (y - x) * (z - y) < 0]
	ans.append(str(len(pp) + 2))
	ans.append(' '.join(map(str, [p[0]] + pp + [p[-1]])))
print('\n'.join(ans))


import sys
input = sys.stdin.buffer.readline
t = int(input())
while t:
	t -= 1
	n = int(input())
	arr = list(map(int, input().split()))
	ans = [arr[0]]
	for i in range(1, n - 1):
		if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:
			ans.append(arr[i])
		elif arr[i] < arr[i - 1] and arr[i] < arr[i + 1]:
			ans.append(arr[i])
	ans.append(arr[-1])
	print(len(ans))
	for x in ans:
		print(x, end=' ')
	print()


def f(a, b, c):
	if a > b and b > c:
		return True
	if a < b and b < c:
		return True
	return False
for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	l = []
	if n == 2:
		print(2)
		print(*p)
	else:
		for i in range(n - 2):
			if f(p[i], p[i + 1], p[i + 2]):
				l.append(i + 1)
		print(n - len(l))
		s = []
		l += [-1]
		j = 0
		for i in range(n):
			if i != l[j]:
				s.append(p[i])
			else:
				j += 1
		print(*s)


for _ in range(int(input())):
	n = int(input())
	lst = [int(x) for x in input().split()]
	lt = []
	for i in range(len(lst)):
		if i == 0 or i == len(lst) - 1 or (lst[i] > lst[i - 1] and lst[i] > lst[i + 1]) or (lst[i] < lst[i - 1] and lst[i] < lst[i + 1]):
			lt.append(str(lst[i]))
	print(len(lt))
	print(' '.join(lt))


t = int(input())
for _ in range(t):
	n = int(input())
	P = list(map(int, input().split(' ')))
	out = [P[0]]
	for i in range(1, n - 1):
		if P[i] > P[i - 1] and P[i] > P[i + 1] or (P[i] < P[i - 1] and P[i] < P[i + 1]):
			out.append(P[i])
	out.append(P[-1])
	print(len(out))
	print(*out)


for _ in range(int(input())):
	n = int(input())
	A = [int(_) for _ in input().split()]
	X = [A[0]]
	for _ in range(n - 2):
		if A[_] - A[_ + 1] < 0 and A[_ + 1] - A[_ + 2] < 0 or (A[_] - A[_ + 1] >= 0 and A[_ + 1] - A[_ + 2] >= 0):
			pass
		else:
			X.append(A[_ + 1])
	X.append(A[-1])
	print(len(X))
	print(*X)


t = int(input())
for loop in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	a = p
	ans = []
	for i in range(n):
		if i == 0 or i == n - 1:
			ans.append(p[i])
		elif a[i - 1] <= a[i] <= a[i + 1]:
			continue
		elif a[i - 1] >= a[i] >= a[i + 1]:
			continue
		else:
			ans.append(p[i])
	print(len(ans))
	print(*ans)


import sys
import math
import itertools
import functools
import collections
import operator
import fileinput
import copy
ORDA = 97

def ii():
	return int(input())

def mi():
	return map(int, input().split())

def li():
	return [int(i) for i in input().split()]

def lcm(a, b):
	return abs(a * b) // math.gcd(a, b)

def revn(n):
	return str(n)[::-1]

def dd():
	return collections.defaultdict(int)

def ddl():
	return collections.defaultdict(list)

def sieve(n):
	if n < 2:
		return list()
	prime = [True for _ in range(n + 1)]
	p = 3
	while p * p <= n:
		if prime[p]:
			for i in range(p * 2, n + 1, p):
				prime[i] = False
		p += 2
	r = [2]
	for p in range(3, n + 1, 2):
		if prime[p]:
			r.append(p)
	return r

def divs(n, start=1):
	r = []
	for i in range(start, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				r.append(i)
			else:
				r.extend([i, n // i])
	return r

def divn(n, primes):
	divs_number = 1
	for i in primes:
		if n == 1:
			return divs_number
		t = 1
		while n % i == 0:
			t += 1
			n //= i
		divs_number *= t

def prime(n):
	if n == 2:
		return True
	if n % 2 == 0 or n <= 1:
		return False
	sqr = int(math.sqrt(n)) + 1
	for d in range(3, sqr, 2):
		if n % d == 0:
			return False
	return True

def convn(number, base):
	newnumber = 0
	while number > 0:
		newnumber += number % base
		number //= base
	return newnumber

def cdiv(n, k):
	return n // k + (n % k != 0)

def ispal(s):
	for i in range(len(s) // 2 + 1):
		if s[i] != s[-i - 1]:
			return False
	return True
for _ in range(ii()):
	n = ii()
	p = li()
	ans = [p[0]]
	for i in range(1, n - 1):
		if p[i - 1] < p[i] > p[i + 1] or p[i - 1] > p[i] < p[i + 1]:
			ans.append(p[i])
	ans.append(p[-1])
	print(len(ans))
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = []
	f = False
	if a[0] > a[1]:
		f = True
	r = -1
	ans.append(a[0])
	for i in range(1, n):
		if f == False:
			if i == n - 1:
				r = a[i]
				r = a[i]
				ans.append(r)
			elif a[i] < a[i + 1]:
				r = a[i]
			else:
				r = a[i]
				ans.append(r)
				r = -1
				f = True
		elif i == n - 1:
			r = a[i]
			r = a[i]
			ans.append(r)
		elif a[i] > a[i + 1]:
			r = a[i]
		else:
			r = a[i]
			ans.append(r)
			f = False
	print(len(ans))
	print(*ans)


t = int(input())
l = []
for i in range(t):
	n = int(input())
	s = list(map(int, input().split()))
	l.append(s)
for j in l:
	l1 = [j[0]]
	for k in range(1, len(j) - 1):
		if j[k] >= j[k - 1] and j[k] <= j[k + 1] or (j[k] <= j[k - 1] and j[k] >= j[k + 1]):
			continue
		else:
			l1.append(j[k])
	l1.append(j[-1])
	print(len(l1), end=' ')
	for m in l1:
		print(m, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	arr = [int(x) for x in input().split()]
	ans = 0
	res = []
	i = 0
	while i < n:
		if i == n - 1:
			res.append(arr[i])
			break
		if arr[i + 1] > arr[i]:
			start = i
			res.append(arr[start])
			while i < n - 1 and arr[i + 1] >= arr[i]:
				i += 1
		else:
			start = i
			res.append(arr[start])
			while i < n - 1 and arr[i + 1] < arr[i]:
				i += 1
	print(len(res))
	for i in res:
		print(i, end=' ')
	print()


for xyz in range(0, int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	a = []
	a.append(l[0])
	for i in range(1, n - 1):
		if l[i] > l[i - 1] and l[i] > l[i + 1]:
			a.append(l[i])
		elif l[i] < l[i - 1] and l[i] < l[i + 1]:
			a.append(l[i])
	a.append(l[-1])
	print(len(a))
	print(*a)


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	arr = list(map(int, input().split()))
	if n == 2:
		print('2')
		print(arr[0], ' ', arr[1])
	else:
		i = 0
		j = 1
		k = 2
		f = 0
		c = 2
		while k <= n - 1:
			a = abs(arr[i] - arr[j]) + abs(arr[j] - arr[k])
			if a == abs(arr[k] - arr[i]):
				arr[j] = -1
				j += 1
				k += 1
			else:
				c += 1
				i = j
				j += 1
				k += 1
		print(c)
		for i in range(n):
			if arr[i] != -1:
				print(arr[i], end=' ')
		print()


import os
os_input = os.read(0, int(10000000.0)).split()
os_input_pos = -1
answer_list = []

def read_s():
	global os_input_pos
	os_input_pos += 1
	return os_input[os_input_pos].decode()

def read_i():
	return int(read_s())

def write_s(v):
	answer_list.append(v)

def write_i(v):
	write_s(str(v))

def print_ans():
	os.write(1, '\n'.join(answer_list).encode())
T = read_i()
while T:
	T -= 1
	n = read_i()
	a = [read_i(), read_i()]
	for i in range(2, n):
		v = read_i()
		if (a[-2] - a[-1]) * (a[-1] - v) >= 0:
			a[-1] = v
		else:
			a.append(v)
	write_i(len(a))
	write_s(' '.join([str(x) for x in a]))
print_ans()


import sys
pprint = lambda s: print(' '.join(map(str, s)))
input = lambda : sys.stdin.readline().strip()
ipnut = input

def f(a):
	o = a[0]
	all = a[1]
	z = all - o
	return min(o, z)
for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [a[0]]
	t = -1
	for i in range(1, n):
		if t == -1:
			if ans[-1] == a[i]:
				continue
			else:
				ans.append(a[i])
				t = int(ans[-2] < ans[-1])
		elif ans[-1] == a[i]:
			continue
		elif t:
			if a[i] > ans[-1]:
				ans[-1] = a[i]
			else:
				t = 0
				ans.append(a[i])
		elif a[i] < ans[-1]:
			ans[-1] = a[i]
		else:
			t = 1
			ans.append(a[i])
	print(len(ans))
	pprint(ans)


def f(n, l):
	output = [l[0]]
	for i in range(1, n - 1):
		if (l[i] - l[i - 1]) * (l[i + 1] - l[i]) < 0:
			output.append(l[i])
	output.append(l[-1])
	return str(len(output)) + '\n' + ' '.join([str(x) for x in output])
numberofcases = int(input())
for _ in range(numberofcases):
	n = int(input())
	l = [int(t) for t in input().split()]
	print(f(n, l))


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l2 = [l[0]]
	for i in range(1, n - 1):
		if l[i] > l[i - 1] and l[i] > l[i + 1] or (l[i] < l[i - 1] and l[i] < l[i + 1]):
			l2.append(l[i])
	l2.append(l[-1])
	print(len(l2))
	print(' '.join(map(str, l2)))


for _ in range(int(input())):
	n = int(input())
	s = [int(i) for i in input().split()]
	s = s + [s[-1]]
	(l, r) = (0, 1)
	d = []
	while r <= n:
		if s[l] < s[r]:
			a = s[l]
			while s[l] < s[r]:
				r += 1
				l += 1
			d.append(a)
			d.append(s[r - 1])
			l = r - 1
		elif s[l] > s[r]:
			a = s[l]
			while s[l] > s[r]:
				r += 1
				l += 1
			d.append(a)
			d.append(s[r - 1])
			l = r - 1
		else:
			break
	z = [] if len(s) > 2 else [s[0]]
	e = set()
	for i in range(len(d)):
		if d[i] not in e:
			z.append(d[i])
			e.add(d[i])
	print(len(z))
	print(*z)


import math
import sys
input = sys.stdin.readline
t = int(input())
result = []
for i in range(t):
	n = int(input())
	p = [int(_) for _ in input().split()]
	rem = [False] * n
	for i in range(1, n - 1):
		if (p[i + 1] - p[i]) * (p[i] - p[i - 1]) > 0:
			rem[i] = True
	result.append(str(n - sum(rem)))
	arr = []
	for i in range(n):
		if rem[i] == False:
			arr.append(p[i])
	result.append(' '.join(map(str, arr)))
print('\n'.join(result))


from sys import stdin, stdout
LI = lambda : list(map(int, input().split()))
MAP = lambda : map(int, input().split())
IN = lambda : int(input())
S = lambda : input()
import math
from collections import Counter

def solve():
	n = IN()
	a = LI()
	b = [a[0]]
	i = 1
	if n == 2:
		print(n)
		print(*a)
		return
	while i < n - 1:
		if abs(a[i] - a[i - 1]) + abs(a[i] - a[i + 1]) == abs(a[i - 1] - a[i + 1]):
			i += 1
		else:
			b.append(a[i])
			i += 1
	b.append(a[-1])
	print(len(b))
	print(*b)
for i in range(IN()):
	solve()


import os
import heapq
import sys
import bisect
import math
import operator
from collections import defaultdict
from io import BytesIO, IOBase

def inar():
	return [int(k) for k in input().split()]

def main():
	for _ in range(int(input())):
		n = int(input())
		arr = inar()
		temp = -1
		res = [arr[0]]
		for i in range(1, n):
			if temp == -1:
				if arr[i] > arr[i - 1]:
					temp = 1
				else:
					temp = 2
			elif temp == 1:
				if arr[i] > arr[i - 1]:
					continue
				else:
					res.append(arr[i - 1])
					temp = 2
			elif arr[i] < arr[i - 1]:
				continue
			else:
				res.append(arr[i - 1])
				temp = 1
		if arr[-1] not in res:
			res.append(arr[-1])
		print(len(res))
		print(*res)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


a = int(input())
for _ in range(a):
	le = int(input())
	count = le
	boo = list(map(int, input().split()))
	hi = 0
	for i in range(le - 2):
		if boo[i + 1 - hi] > boo[i - hi] and boo[i + 2 - hi] > boo[i + 1 - hi]:
			del boo[i + 1 - hi]
			hi += 1
		elif boo[i + 1 - hi] < boo[i - hi] and boo[i - hi + 2] < boo[i - hi + 1]:
			del boo[i + 1 - hi]
			hi += 1
	print(len(boo))
	print(*boo)


import sys
input = sys.stdin.readline

def main():
	t = int(input())
	for _ in range(t):
		N = int(input())
		P = [int(x) for x in input().split()]
		ans = []
		zogen = 0
		ans.append(P[0])
		for i in range(N - 1):
			p = P[i]
			pp = P[i + 1]
			if zogen == 0:
				if p > pp:
					zogen = -1
				elif p < pp:
					zogen = 1
				if i == N - 2:
					if ans[-1] != pp:
						ans.append(pp)
			else:
				if zogen == 1 and p > pp:
					ans.append(p)
					zogen = -1
				elif zogen == -1 and p < pp:
					zogen = 1
					ans.append(p)
				if i == N - 2:
					if ans[-1] != pp:
						ans.append(pp)
		if len(ans) == 1:
			print(0)
		else:
			print(len(ans))
			print(*ans)
main()


import math
t = int(input())
for i in range(t):
	n = int(input())
	data = list(map(int, input().split()))
	diff = []
	up = 0
	for j in range(n):
		if j == 0:
			diff.append(str(data[j]))
		elif j == 1:
			if data[j] > data[j - 1]:
				up = 1
			else:
				up = 0
		elif up == 1 and data[j] < data[j - 1]:
			up = 0
			diff.append(str(data[j - 1]))
		elif up == 0 and data[j] > data[j - 1]:
			up = 1
			diff.append(str(data[j - 1]))
	diff.append(str(data[n - 1]))
	print(len(diff))
	reem = ' '.join(diff)
	print(reem)


for _ in range(int(input())):
	n = int(input())
	a = []
	for x in map(int, input().split()):
		if len(a) >= 2 and (a[-2] < a[-1] < x or a[-2] > a[-1] > x):
			a.pop()
		a += (x,)
	print(len(a))
	print(*a)


def a():
	(n, k) = (int(x) for x in input().split())
	arr = [int(x) for x in input().split()]

	def psum(ar):
		ps = [0]
		for x in ar:
			ps.append(x + ps[-1])
		return ps

	def solve(ln, x, ps):
		for i in range(ln, 0, -1):
			if ps[i] % x != 0:
				return i
		return -1
	prefsum = psum(arr)
	ans = solve(n, k, prefsum)
	prefsum = psum(arr[::-1])
	ans = max(ans, solve(n, k, prefsum))
	print(ans)

def b():
	n = int(input())
	arr = [int(x) for x in input().split()]
	if arr[0] - arr[1] < 0:
		dir = -1
	else:
		dir = 1
	ans = [arr[0]]
	prev = arr[1]
	for i in range(2, n):
		curr = arr[i]
		if prev - curr < 0:
			d = -1
		else:
			d = 1
		if d != dir:
			dir = d
			ans.append(prev)
		prev = curr
	ans.append(arr[-1])
	print(len(ans))
	print(*ans)
for _ in range(int(input())):
	b()


from sys import stdin, stdout
import math, sys, heapq
from itertools import permutations, combinations
from collections import defaultdict, deque, OrderedDict
from os import path
import random
import bisect as bi

def yes():
	print('YES')

def no():
	print('NO')
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

	def I():
		return int(input())

	def In():
		return map(int, input().split())
else:

	def I():
		return int(stdin.readline())

	def In():
		return map(int, stdin.readline().split())

def dict(a):
	d = {}
	for x in a:
		if d.get(x, -1) != -1:
			d[x] += 1
		else:
			d[x] = 1
	return d

def find_gt(a, x):
	i = bi.bisect_left(a, x)
	if i != len(a):
		return i
	else:
		return -1

def main():
	try:
		n = I()
		l = list(In())
		if n == 2:
			print(2)
			print(*l)
		else:
			q = [l[0]]
			for i in range(1, n - 1):
				if l[i - 1] < l[i] and l[i] > l[i + 1]:
					q.append(l[i])
				elif l[i - 1] > l[i] and l[i + 1] > l[i]:
					q.append(l[i])
				else:
					continue
			ans = 0
			q.append(l[-1])
			print(len(q))
			print(*q)
	except:
		pass
M = 998244353
P = 1000000007
for _ in range(I()):
	main()


x = int(input())
for xxx in range(x):
	npp = int(input())
	sublist = list(map(int, input().split()))
	li = [sublist[0]]
	for i in range(1, npp - 1):
		if sublist[i - 1] < sublist[i]:
			if sublist[i + 1] < sublist[i]:
				li.append(sublist[i])
		elif sublist[i - 1] > sublist[i]:
			if sublist[i + 1] > sublist[i]:
				li.append(sublist[i])
	li.append(sublist[-1])
	ans = len(li)
	print(ans)
	for i in li:
		print(i, end=' ')
	print()


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	N = int(input())
	a = list(map(int, input().split()))
	res = a[:]
	if a[1] - a[0] > 0:
		up = 1
	for i in range(1, N - 1):
		if a[i - 1] < a[i] < a[i + 1]:
			res[i] = 0
		if a[i - 1] > a[i] > a[i + 1]:
			res[i] = 0
	rres = []
	for x in res:
		if x:
			rres.append(x)
	print(len(rres))
	print(*rres)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	out = [a[0]]
	d = a[0] < a[1]
	for (x, y) in zip(a[1:], a[2:]):
		if (x < y) == d:
			continue
		else:
			d = x < y
			out.append(x)
	out.append(a[-1])
	print(len(out))
	print(*out)


import sys

def ii():
	return sys.stdin.readline().strip()

def idata():
	return [int(x) for x in ii().split()]

def solve_of_problem():
	n = int(ii())
	data = idata()
	ans = [data[0]]
	for i in range(1, n - 1):
		if data[i - 1] < data[i] > data[i + 1] or data[i - 1] > data[i] < data[i + 1]:
			ans += [data[i]]
	print(len(ans) + 1)
	print(*ans, data[-1])
	return
for ______ in range(int(ii())):
	solve_of_problem()


for _ in range(int(input())):
	i_liczb = int(input())
	liczby = [int(x) for x in input().split()]
	if i_liczb == 2:
		print(i_liczb)
		print(*liczby)
		continue
	wyniki = []
	(l1, l2, l3) = (liczby[0], liczby[1], liczby[2])
	for x in range(3, i_liczb):
		if l1 <= l2 <= l3 or l1 >= l2 >= l3:
			l2 = l3
			l3 = liczby[x]
		else:
			wyniki.append(l1)
			l1 = l2
			l2 = l3
			l3 = liczby[x]
	wyniki.append(l1)
	if not (l1 <= l2 <= l3 or l1 >= l2 >= l3):
		wyniki.append(l2)
	wyniki.append(l3)
	print(len(wyniki))
	print(*wyniki)


T = int(input())
for _ in range(T):
	N = int(input())
	a = [int(x) for x in input().split(' ')]
	ans = [a[0]]
	for i in range(1, N - 1):
		if a[i - 1] > a[i] and a[i] < a[i + 1]:
			ans.append(a[i])
		elif a[i - 1] < a[i] and a[i] > a[i + 1]:
			ans.append(a[i])
	ans.append(a[-1])
	print(len(ans))
	print(' '.join((str(i) for i in ans)))


from sys import stdin
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	arr = list(map(int, stdin.readline().split()))
	fin = [arr[0], arr[1]]
	for i in range(2, n):
		if (arr[i] - fin[-1]) * (fin[-1] - fin[-2]) > 0:
			fin.pop()
		fin.append(arr[i])
	print(len(fin))
	for i in fin:
		print(i, end=' ')
	print('')


t = int(input())
for _ in range(t):
	n = int(input())
	p = [int(x) for x in input().split()]
	inc = p[1] - p[0] > 0
	prev = p[1]
	out = [p[0], p[1]]
	for i in range(1, n):
		if p[i] == prev:
			continue
		if p[i] > prev and inc:
			out[-1] = p[i]
		elif p[i] < prev and (not inc):
			out[-1] = p[i]
		else:
			out.append(p[i])
			inc = not inc
		prev = p[i]
	print(len(out))
	print(' '.join(map(str, out)))


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = [l[0]]
	for i in range(1, n - 1):
		if l[i] > l[i - 1] and l[i] > l[i + 1] or (l[i] < l[i - 1] and l[i] < l[i + 1]):
			ans.append(l[i])
	ans.append(l[n - 1])
	print(len(ans))
	print(*ans)


t = int(input())
for helloworld in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	s = 'What'
	j = 0
	res = [0] * n
	gsda = ''
	for i in range(1, n):
		if a[i] > a[i - 1]:
			if s == True:
				pass
			else:
				res[j] = a[i - 1]
				j += 1
				s = True
		elif s == False:
			pass
		else:
			res[j] = a[i - 1]
			j += 1
			s = False
	res[-1] = a[-1]
	j = 0
	for i in range(n):
		if res[i] != 0:
			j += 1
			gsda += str(res[i]) + ' '
	print(j)
	print(gsda)


for _ in range(int(input())):
	n = int(input())
	k = 0
	t = [*map(int, input().split())]
	k += 1
	ans = [t[0]]
	for i in range(1, n - 1):
		if t[i + 1] < t[i] and t[i - 1] < t[i]:
			ans.append(t[i])
		elif t[i + 1] > t[i] and t[i - 1] > t[i]:
			ans.append(t[i])
	ans.append(t[-1])
	print(len(ans))
	print(*ans)


for ttt in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	x = [a[0]]
	for i in range(1, n - 1):
		if a[i - 1] <= a[i] and a[i + 1] >= a[i] or (a[i - 1] >= a[i] and a[i + 1] <= a[i]):
			continue
		x.append(a[i])
	x.append(a[n - 1])
	print(len(x))
	print(*x)


from sys import stdin, stdout, setrecursionlimit
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	ok = []
	for i in range(1, n - 1):
		if a[i - 1] < a[i] < a[i + 1] or a[i - 1] > a[i] > a[i + 1]:
			ok.append(i)
	print(n - len(ok))
	curok = 0
	for i in range(n):
		if curok < len(ok) and i == ok[curok]:
			curok += 1
		else:
			print(a[i], end=' ')
	print()


t = int(input())
for i in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	l = [p[0]]
	j = 1
	check = 0
	for j in range(1, n - 1):
		if check == 0:
			if l[-1] < p[j]:
				check = 1
			else:
				check = -1
		if check == 1:
			if p[j] > p[j + 1]:
				l.append(p[j])
				check = 0
		if check == -1:
			if p[j] < p[j + 1]:
				l.append(p[j])
				check = 0
	if l[-1] != p[-1]:
		l.append(p[-1])
	print(len(l))
	print(*l)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = [x for x in map(int, input().split(' '))]
	if n == 2:
		print(2)
		print(arr[0], arr[1])
		continue
	(a, b, c) = (0, 1, 2)
	newarr = []
	newarr.append(arr[a])
	while c < len(arr):
		if abs(arr[c] - newarr[a]) >= abs(arr[b] - newarr[a]) + abs(arr[c] - arr[b]):
			b = c
			c += 1
		else:
			newarr.append(arr[b])
			(a, b, c) = (a + 1, b + 1, c + 1)
	newarr.append(arr[c - 1])
	print(len(newarr))
	for v in newarr:
		print(v, end=' ')
	print()


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = [int(x) for x in input().split()]
	p = [None] * n
	p[0] = 1
	p[n - 1] = 1
	for i in range(1, n - 1):
		if a[i] > a[i - 1] and a[i] > a[i + 1]:
			p[i] = 1
		elif a[i] < a[i - 1] and a[i] < a[i + 1]:
			p[i] = 1
		else:
			p[i] = 0
	ans = []
	for i in range(n):
		if p[i] == 1:
			ans.append(a[i])
	print(len(ans))
	for i in ans:
		print(i, end=' ')
	print()


for _ in range(int(input())):
	n = map(int, input())
	arr = list(map(int, input().split()))
	ans = [arr[0]]
	sign = (arr[1] - arr[0]) // abs(arr[1] - arr[0])
	for i in range(2, len(arr)):
		if (arr[i] - arr[i - 1]) // abs(arr[i] - arr[i - 1]) != sign:
			ans.append(arr[i - 1])
			sign = (arr[i] - arr[i - 1]) // abs(arr[i] - arr[i - 1])
	if arr[-1] not in ans:
		ans.append(arr[-1])
	print(len(ans))
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	s = [l[0]]
	for i in range(1, n - 1):
		if l[i] > l[i - 1] and l[i] < l[i + 1] or (l[i] < l[i - 1] and l[i] > l[i + 1]):
			continue
		else:
			s.append(l[i])
	s.append(l[-1])
	print(len(s))
	print(*s)


import sys
INF = 10 ** 20
MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br

def solve():
	(n,) = I()
	a = I()
	ans = []
	ok = a[1] > a[0]
	ans.append(a[0])
	for i in range(1, n):
		if ok:
			if a[i] > a[i - 1]:
				continue
			ans.append(a[i - 1])
			ok ^= 1
		else:
			if a[i] < a[i - 1]:
				continue
			ans.append(a[i - 1])
			ok ^= 1
	if ans[-1] != a[-1]:
		ans.append(a[-1])
	print(len(ans))
	print(*ans)
(t,) = I()
while t:
	t -= 1
	solve()


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		perm = [int(x) for x in input().split()]
		result = [perm[0]]
		for i in range(1, n - 1):
			(leftVal, rightVal) = (perm[i - 1], perm[i + 1])
			curVal = perm[i]
			curDiff = abs(leftVal - curVal) + abs(rightVal - curVal)
			newDiff = abs(leftVal - rightVal)
			if newDiff < curDiff:
				result.append(curVal)
		result.append(perm[-1])
		print(len(result))
		print(*result)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


t = int(input())
while t > 0:
	n = int(input())
	arr = list(map(int, input().split()))
	ar = [arr[0]]
	for i in range(1, n - 1):
		if min(arr[i - 1], arr[i], arr[i + 1]) == arr[i] or max(arr[i - 1], arr[i], arr[i + 1]) == arr[i]:
			ar.append(arr[i])
	ar.append(arr[-1])
	print(len(ar))
	print(*ar)
	t -= 1


def solution():
	n = int(input())
	p = list(map(int, input().split()))
	plus = p[1] > p[0]
	count = 1
	lst = []
	temp = p[0]
	lst.append(temp)
	for i in range(1, n - 1):
		if plus and p[i] <= p[i + 1]:
			continue
		if not plus and p[i] >= p[i + 1]:
			continue
		else:
			lst.append(p[i])
			plus = not plus
			count += 1
	lst.append(p[n - 1])
	count += 1
	print(count)
	for li in lst:
		print(li, end=' ')
	print()
T = int(input())
for t in range(T):
	solution()


t = int(input())

def solve(arr):
	n = len(arr)
	ans = []
	for i in range(n):
		if i == 0 or i == n - 1:
			ans.append(arr[i])
		elif arr[i - 1] > arr[i] < arr[i + 1] or arr[i - 1] < arr[i] > arr[i + 1]:
			ans.append(arr[i])
	return ans
for _ in range(t):
	n = int(input())
	(*arr,) = map(int, input().split())
	ans = solve(arr)
	print(len(ans))
	print(*ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [p[0]]
	for i in range(n - 2):
		if (p[i] - p[i + 1]) * (p[i + 1] - p[i + 2]) < 0:
			ans.append(p[i + 1])
	ans.append(p[-1])
	print(len(ans))
	print(*ans)


t = int(input())
for i in range(t):
	n = int(input())
	ar = [int(i) for i in input().split()]
	seq = [ar[0]]
	run = ar[0]
	count = False
	for j in range(n - 1):
		if run > ar[j + 1]:
			run = ar[j + 1]
			if count == False:
				seq.append(run)
				sign = False
				count = True
			elif sign == False:
				seq[-1] = run
			else:
				seq.append(run)
				sign = False
		elif run < ar[j + 1]:
			run = ar[j + 1]
			if count == False:
				seq.append(run)
				sign = True
				count = True
			elif sign == True:
				seq[-1] = run
			else:
				seq.append(run)
				sign = True
		else:
			pass
	print(len(seq))
	print(' '.join((str(i) for i in seq)))


t = int(input())
for _ in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	S = [A[0]]
	sgn = 0
	cnt = 1
	for i in range(1, n):
		if sgn == 0:
			S.append(A[i])
			sgn = 2 * (A[i - 1] < A[i]) - 1
			cnt += 1
		elif sgn == 1:
			if S[cnt - 1] < A[i]:
				S[cnt - 1] = A[i]
			else:
				S.append(A[i])
				sgn = -1
				cnt += 1
		elif sgn == -1:
			if S[cnt - 1] > A[i]:
				S[cnt - 1] = A[i]
			else:
				S.append(A[i])
				sgn = 1
				cnt += 1
	print(cnt)
	for i in range(cnt):
		print(S[i], end=' ' * (i != cnt - 1))
	print()


from sys import stdin
import math
t = int(input())
for _ in range(t):
	n = int(stdin.readline())
	arr = list(map(int, stdin.readline().rstrip().split(' ')))
	answer = []
	answer.append(arr[0])
	i = 0
	while i < n - 1:
		if arr[i + 1] > arr[i]:
			j = i + 1
			while j < n and arr[j] > arr[j - 1]:
				j += 1
		else:
			j = i + 1
			while j < n and arr[j] < arr[j - 1]:
				j += 1
		answer.append(arr[min(n - 1, j - 1)])
		i = j - 1
	print(len(answer))
	print(*answer)


T = int(input())
for t in range(T):
	n = int(input())
	A = [int(i) for i in input().split()]
	ans = [A[0]]
	for i in range(1, n - 1):
		if (A[i] - A[i - 1]) * (A[i] - A[i + 1]) > 0:
			ans.append(A[i])
	ans.append(A[-1])
	print(len(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	last = [p[0]]
	for i in range(1, len(p) - 1):
		if abs(last[-1] - p[i]) + abs(p[i] - p[i + 1]) > abs(last[-1] - p[i + 1]):
			last.append(p[i])
	last.append(p[-1])
	print(len(last))
	print(' '.join(map(str, last)))


for i in range(int(input())):
	a = int(input())
	t = list(map(int, input().split()))
	f = []
	for k in range(a):
		if k == 0:
			f.append(t[k])
		elif k == a - 1:
			f.append(t[k])
		elif t[k - 1] < t[k] > t[k + 1]:
			f.append(t[k])
		elif t[k - 1] > t[k] < t[k + 1]:
			f.append(t[k])
	print(len(f))
	print(*f)


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	s = 2
	l = [a[0]]
	k = -1
	for i in range(1, n - 1):
		(x, y, z) = (a[i - 1], a[i], a[i + 1])
		if x < y > z:
			s += 1
			l.append(y)
		if x > y < z:
			s += 1
			l.append(y)
	l.append(a[-1])
	print(s)
	print(*l)


from sys import stdin

def get_int():
	return int(stdin.readline().strip())

def get_tuple():
	return map(int, stdin.readline().split())

def get_list():
	return list(map(int, stdin.readline().split()))

def main():
	n = get_int()
	ls = get_list()
	inc = True if ls[1] > ls[0] else False
	stack = [ls[0], ls[1]]
	for val in ls[2:]:
		if inc:
			if val > stack[-1]:
				stack.pop(-1)
				stack.append(val)
			else:
				stack.append(val)
				inc = False
		elif val < stack[-1]:
			stack.pop(-1)
			stack.append(val)
		else:
			stack.append(val)
			inc = True
	print(len(stack))
	print(*stack)
TestCases = True
if TestCases:
	for i in range(get_int()):
		main()
else:
	main()


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	val = [l[0]]
	for i in range(1, n - 1):
		if l[i - 1] < l[i] and l[i + 1] < l[i]:
			val.append(l[i])
		elif l[i - 1] > l[i] and l[i + 1] > l[i]:
			val.append(l[i])
	val.append(l[-1])
	print(len(val))
	for i in val:
		print(i, end=' ')
	print()


for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [a[0]]
	ans1 = 0
	for i in range(1, n - 1):
		if abs(a[i] - ans[-1]) + abs(a[i] - a[i + 1]) > abs(a[i + 1] - ans[-1]):
			ans.append(a[i])
	ans.append(a[n - 1])
	for i in range(1, len(ans)):
		ans1 += abs(ans[i] - ans[i - 1])
	print(len(ans))
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	su = 0
	for i in range(n - 1):
		su += abs(l[i + 1] - l[i])
	l1 = [l[0]]
	(z, cnt) = (0, 0)
	if l[1] > l[0]:
		for i in range(n - 1):
			if z == 1:
				if l[i] > l[i + 1]:
					continue
				else:
					z = 0
					l1.append(l[i])
			elif z == 0:
				if l[i + 1] > l[i]:
					continue
				else:
					z = 1
					l1.append(l[i])
	else:
		for i in range(n - 1):
			if z == 0:
				if l[i] > l[i + 1]:
					continue
				else:
					z = 1
					l1.append(l[i])
			elif z == 1:
				if l[i + 1] > l[i]:
					continue
				else:
					z = 0
					l1.append(l[i])
	l1.append(l[-1])
	print(len(l1))
	print(*l1)


for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	diff = -1
	if a[0] > a[1]:
		ans = []
	else:
		ans = [a[0]]
	inc = False
	for i in range(1, n):
		if a[i - 1] < a[i] and inc == True:
			ans.append(a[i - 1])
			inc = False
		elif a[i - 1] > a[i] and inc == False:
			ans.append(a[i - 1])
			inc = True
	ans.append(a[-1])
	if len(ans) == 1:
		print(2)
		print(ans[0], ans[0])
	else:
		print(len(ans))
		print(*ans, sep=' ')


def lcm(a, b):
	return a * b // gcd(a, b)

def inin():
	return int(input())

def inar():
	return list(map(int, input().split()))

def ar(element, size):
	return [element for i in range(size)]

def yes():
	print('Yes')

def no():
	print('No')
Testcase = inin()
for _ in range(Testcase):
	n = inin()
	a = inar()
	ans = []
	ans.append(a[0])
	curr = a[0]
	i = 1
	while i < n:
		if curr < a[i]:
			while i < n and curr < a[i]:
				curr = a[i]
				i += 1
			ans.append(curr)
		elif curr > a[i]:
			while i < n and curr > a[i]:
				curr = a[i]
				i += 1
			ans.append(curr)
	print(len(ans))
	print(*ans)


for _ in range(int(input())):
	(n, a) = (int(input()), list(map(int, input().split())))
	(b, ans) = ([0], [a[0]])
	for i in range(1, n):
		if a[i] > a[i - 1]:
			b.append(1)
		else:
			b.append(-1)
	for i in range(1, n - 1):
		if b[i] != b[i + 1]:
			ans.append(a[i])
	print(len(ans) + 1)
	for i in range(len(ans)):
		print(ans[i], end=' ')
	print(a[n - 1])


def ans(p):
	ret = []
	for i in range(len(p)):
		if i == 0:
			ret += [p[i]]
		elif i == len(p) - 1:
			ret += [p[i]]
		elif p[i - 1] <= p[i] <= p[i + 1]:
			continue
		elif p[i - 1] >= p[i] >= p[i + 1]:
			continue
		else:
			ret += [p[i]]
	return ret
T = int(input())
for t in range(T):
	input()
	p = input().split(' ')
	p = [int(x) for x in p]
	a = ans(p)
	print(len(a))
	print(' '.join((str(x) for x in a)))


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	L = list(map(int, input().split()))
	val = []
	for i in range(n - 1):
		val.append(L[i + 1] - L[i])
	t = val[0]
	ans = [L[0]]
	for i in range(1, n - 1):
		if t > 0:
			if val[i] > 0:
				continue
			if val[i] < 0:
				ans.append(L[i])
				t = -1
		if t < 0:
			if val[i] < 0:
				continue
			if val[i] > 0:
				ans.append(L[i])
				t = 1
	ans.append(L[-1])
	print(len(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	r = []
	r.append(a[0])
	i = 1
	while i < n - 1:
		if a[i] > a[i - 1] and a[i] > a[i + 1]:
			r.append(a[i])
		elif a[i] < a[i - 1] and a[i] < a[i + 1]:
			r.append(a[i])
		i = i + 1
	r.append(a[n - 1])
	x = len(r)
	print(x)
	for i in range(x):
		print(r[i], end=' ')
	print()


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	l1 = [l[0]]
	j = 1
	while j < n - 1:
		if l[j - 1] < l[j] and l[j + 1] < l[j]:
			l1.append(l[j])
		elif l[j - 1] > l[j] and l[j + 1] > l[j]:
			l1.append(l[j])
		j += 1
	if l1[-1] != l[-1]:
		l1.append(l[-1])
	print(len(l1))
	print(*l1)


import math
import sys
import collections
from collections import defaultdict
from sys import stdin, stdout
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = []
	ans.append(arr[0])
	for i in range(1, n - 1):
		if arr[i - 1] < arr[i] and arr[i] > arr[i + 1] or (arr[i - 1] > arr[i] and arr[i] < arr[i + 1]):
			ans.append(arr[i])
	ans.append(arr[n - 1])
	print(len(ans))
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	a = input().split(' ')
	if n == 1:
		print(0)
		continue
	for i in range(n):
		a[i] = int(a[i])
	s = []
	for i in range(1, n):
		s.append(a[i] - a[i - 1])
	values = []
	i = 0
	while i < n - 1 and s[i] == 0:
		i = i + 1
	if i == n - 1:
		print(0)
		continue
	values.append(i)
	if s[i] > 0:
		trend = 1
	elif s[i] < 0:
		trend = -1
	for j in range(i + 1, n - 1):
		if s[j] < 0 and trend == 1:
			values.append(j)
			trend = -1
		elif s[j] > 0 and trend == -1:
			values.append(j)
			trend = 1
	if n - 1 not in values:
		values.append(n - 1)
	print(len(values))
	for i in values:
		print(a[i], end=' ')
	print()


import math
import sys
from itertools import permutations
input = sys.stdin.readline
t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	dir = False
	if arr[1] - arr[0] > 0:
		dir = True
	ans = [arr[0]]
	for j in range(n - 1):
		if arr[j + 1] - arr[j] > 0:
			if dir == False:
				ans.append(arr[j])
				dir = True
		elif dir == True:
			ans.append(arr[j])
			dir = False
	if ans[-1] != arr[-1]:
		ans.append(arr[-1])
	print(len(ans))
	print(*ans)


import math
t = int(input())
for cnt in range(t):
	n = map(int, input().split())
	a = list(map(int, input().split()))
	num = max(a)
	b = list()
	sum = 0
	for i in a:
		temp = len(b)
		if temp == 0:
			b.append(i)
		if temp >= 1:
			if i != b[temp - 1]:
				b.append(i)
		temp = len(b)
		if temp > 2:
			if abs(b[temp - 1] - b[temp - 2]) + abs(b[temp - 2] - b[temp - 3]) <= abs(b[temp - 1] - b[temp - 3]):
				b.pop(temp - 2)
	print(len(b))
	print(*b, sep=' ')


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	res = [arr[0]]
	if arr[0] < arr[1]:
		flag = True
	else:
		flag = False
	for i in range(1, n - 1):
		if flag == True:
			if arr[i + 1] < arr[i]:
				res.append(arr[i])
				flag = False
		elif arr[i + 1] > arr[i]:
			res.append(arr[i])
			flag = True
	res.append(arr[n - 1])
	print(len(res))
	print(*res)


t = int(input())
for tc in range(t):
	n = int(input())
	lis = list(map(int, input().split()))
	nu1 = [lis[0]]
	nu2 = [lis[0]]
	l1 = 0
	l2 = 0
	if lis[0] < lis[1]:
		for i in range(1, n):
			if l1 == 0:
				if lis[i] >= lis[i - 1]:
					pass
				else:
					nu1.append(lis[i - 1])
					l1 = 1
					l2 = 0
			elif lis[i] <= lis[i - 1]:
				pass
			else:
				nu1.append(lis[i - 1])
				l1 = 0
				l2 = 1
		nu1.append(lis[-1])
	else:
		l1 = 0
		l2 = 0
		for i in range(1, n):
			if l1 == 0:
				if lis[i] <= lis[i - 1]:
					pass
				else:
					nu2.append(lis[i - 1])
					l1 = 1
					l2 = 0
			elif lis[i] >= lis[i - 1]:
				pass
			else:
				nu2.append(lis[i - 1])
				l1 = 0
				l2 = 1
		nu2.append(lis[-1])
	if len(nu1) > len(nu2):
		l1 = len(nu1)
		print(l1)
		for i in nu1:
			print(i, end=' ')
		print()
	else:
		l2 = len(nu2)
		print(l2)
		for i in nu2:
			print(i, end=' ')
		print()


import sys
T = int(sys.stdin.readline().strip())
for t in range(0, T):
	n = int(sys.stdin.readline().strip())
	p = list(map(int, sys.stdin.readline().strip().split()))
	ans = [p[0]]
	for i in range(1, n):
		if p[i] != ans[-1]:
			if len(ans) == 1:
				ans.append(p[i])
			else:
				if (ans[-2] - ans[-1]) * (ans[-1] - p[i]) > 0:
					ans.pop()
				ans.append(p[i])
	print(len(ans))
	print(' '.join(list(map(str, ans))))


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, copy, functools
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
mod2 = 998244353
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return list(map(int, sys.stdin.readline().split()))

def LLI():
	return [list(map(int, l.split())) for l in sys.stdin.readlines()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

def I():
	return int(sys.stdin.readline())

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def pe(s):
	return print(str(s), file=sys.stderr)

def JA(a, sep):
	return sep.join(map(str, a))

def JAA(a, s, t):
	return s.join((t.join(map(str, b)) for b in a))

def IF(c, t, f):
	return t if c else f

def YES(c):
	return IF(c, 'YES', 'NO')

def main():
	t = I()
	rr = []
	for _ in range(t):
		n = I()
		a = LI()
		t = set()
		for i in range(1, n - 1):
			if a[i] == a[i - 1]:
				t.add(i)
			elif a[i - 1] < a[i] < a[i + 1]:
				t.add(i)
			elif a[i - 1] > a[i] > a[i + 1]:
				t.add(i)
		if a[-1] == a[-2]:
			t.add(n - 1)
		r = [a[i] for i in range(n) if i not in t]
		rr.append(len(r))
		rr.append(JA(r, ' '))
	return JA(rr, '\n')
print(main())


import sys
import collections as cc
import bisect as bi
I = lambda : list(map(int, input().split()))
for tc in range(int(input())):
	(n,) = I()
	l = I()
	temp = 1 if l[1] < l[0] else 2
	ans = [0] * n
	for i in range(1, n):
		if l[i] > l[i - 1]:
			ans[i] = ans[i - 1] + 1
		elif l[i] < l[i - 1]:
			ans[i] = ans[i - 1] - 1
	te = [l[0]]
	for i in range(1, n - 1):
		if l[i] > l[i + 1] and l[i] > l[i - 1]:
			te.append(l[i])
		elif l[i] < l[i - 1] and l[i] < l[i + 1]:
			te.append(l[i])
	te.append(l[-1])
	print(len(te))
	print(*te)


t = int(input())
for test in range(t):
	n = int(input())
	l = list(map(int, input().rstrip().split()))
	i = 0
	arr = list()
	arr.append(str(l[0]))
	while i + 1 < n:
		if i + 1 == n - 1 or (l[i] < l[i + 1] and l[i + 1] > l[i + 2]) or (l[i] > l[i + 1] and l[i + 1] < l[i + 2]):
			arr.append(str(l[i + 1]))
		i += 1
	print(len(arr))
	print(' '.join(arr))


for t in range(int(input())):
	n = int(input())
	per = list(map(int, input().split()))
	cur = per[0]
	ans = [str(per[0])]
	if per[0] < per[1]:
		sign = 1
	else:
		sign = -1
	for i in range(1, n - 1):
		if per[i + 1] > per[i]:
			cur_sign = 1
		else:
			cur_sign = -1
		if cur_sign == sign:
			pass
		else:
			sign = cur_sign
			ans += [str(per[i])]
	if str(per[-1]) != ans[-1]:
		ans += [str(per[-1])]
	print(len(ans))
	print(' '.join(ans))


T = int(input())
for test in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	list_ans = [a[0], a[1]]
	for i in range(2, n):
		if abs(list_ans[-1] - list_ans[-2]) < abs(list_ans[-2] - a[i]) >= abs(list_ans[-1] - list_ans[-2]) + abs(list_ans[-1] - a[i]):
			list_ans.pop()
			list_ans.append(a[i])
		elif abs(list_ans[-1] - list_ans[-2]) < abs(list_ans[-1] - list_ans[-2]) + abs(list_ans[-1] - a[i]):
			list_ans.append(a[i])
	print(len(list_ans))
	for el in list_ans:
		print(el, end=' ')


def f(a):
	mx = len(a)
	ans = []
	for i in range(0, mx):
		if i == 0 or i == mx - 1:
			ans.append(a[i])
			continue
		elif (a[i - 1] < a[i]) != (a[i] < a[i + 1]):
			ans.append(a[i])
	print(len(ans))
	return ans
for i in range(int(input())):
	a = input()
	lst = list(map(int, input().strip().split()))
	print(*f(lst))


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	i = 0
	f = 0
	ans = [l[0]]
	if l[0] < l[1]:
		f = 1
	for i in range(1, n):
		if l[i] > l[i - 1]:
			if f == 0:
				ans.append(l[i - 1])
				f = 1
		elif f == 1:
			f = 0
			ans.append(l[i - 1])
	ans.append(l[-1])
	print(len(ans))
	print(*ans)


t = int(input())
for test in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	marr = [arr[0]]
	for i in range(1, n - 1):
		if arr[i - 1] > arr[i] < arr[i + 1] or arr[i - 1] < arr[i] > arr[i + 1]:
			marr.append(arr[i])
	marr.append(arr[n - 1])
	print(len(marr))
	print(*marr)


for _ in range(int(input())):
	n = int(input())
	l = [int(x) for x in input().split()]
	ar = []
	ar.append(l[0])
	for i in range(1, n - 1):
		if l[i - 1] < l[i] and l[i + 1] < l[i]:
			ar.append(l[i])
		elif l[i - 1] > l[i] and l[i + 1] > l[i]:
			ar.append(l[i])
	ar.append(l[n - 1])
	print(len(ar))
	for i in ar:
		print(i, end=' ')
	print()


T = int(input())
for _ in range(T):
	N = int(input())
	P = list(map(int, input().split()))
	if N == 2:
		print(2)
		print(*P)
		continue
	ans = [P[0]]
	for (a, b, c) in zip(P, P[1:], P[2:]):
		if a < b and b > c or (a > b and b < c):
			ans.append(b)
	ans.append(P[-1])
	print(len(ans))
	print(*ans)


from collections import defaultdict as dd
import sys
input = sys.stdin.readline
t = int(input())
while t:
	n = int(input())
	l = list(map(int, input().split()))
	i = 0
	j = 1
	ll = [l[0]]
	ans = 0
	lol = 0
	while j < n and i < n:
		if l[j] == l[j - 1]:
			j += 1
			i += 1
		elif l[j] > l[j - 1]:
			if j != i and lol == -1:
				ll.append(l[j - 1])
				i = j - 1
			lol = 1
			j += 1
		else:
			if j != i and lol == 1:
				ll.append(l[j - 1])
				i = j - 1
			lol = -1
			j += 1
	if ll[-1] != l[n - 1]:
		ll.append(l[n - 1])
	ans = len(ll)
	if ans == 1:
		ans += 1
		ll.append(ll[0])
	print(ans)
	print(*ll)
	t -= 1


t = int(input())
for _ in range(t):
	n = int(input())
	x = list(map(int, input().split()))
	last = 1
	a = []
	a.append(x[0])
	for i in range(1, n):
		if last == 1 and x[i] - x[i - 1] >= 0:
			continue
		elif last == 1 and x[i] - x[i - 1] < 0:
			last = 0
			if i != 1:
				a.append(x[i - 1])
		elif last == 0 and x[i] - x[i - 1] >= 0:
			last = 1
			a.append(x[i - 1])
		else:
			continue
	a.append(x[-1])
	print(len(a))
	print(*a)


t = int(input())
for jack in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	p = [a[0], a[1]]
	up = bool(a[1] > a[0])
	for i in range(2, n):
		if up:
			if a[i] > p[-1]:
				p[-1] = a[i]
			else:
				p.append(a[i])
				up = False
		elif a[i] < p[-1]:
			p[-1] = a[i]
		else:
			p.append(a[i])
			up = True
	print(len(p))
	for i in p:
		print(i, end=' ')
	print()


from sys import stdin, stdout
import collections
import heapq
import itertools
import functools
import math
import operator
import string
ALPHABET = string.ascii_lowercase
DIGITS = string.digits

def read_line():
	return stdin.readline().strip()

def read_int():
	return int(read_line())

def read_arr():
	return read_line().split(' ')

def read_int_arr():
	return [int(x) for x in read_arr()]

def query_interactive(s):
	print(s)
	stdout.flush()

def solve():
	n = read_int()
	p = read_int_arr()
	res = []
	for i in range(n):
		if i == 0 or i == n - 1:
			res.append(p[i])
		elif p[i] > p[i - 1] and p[i] > p[i + 1]:
			res.append(p[i])
		elif p[i] < p[i - 1] and p[i] < p[i + 1]:
			res.append(p[i])
	print(len(res))
	print(*res, sep=' ')

def main():
	T = 1
	T = read_int()
	for _ in range(T):
		solve()
main()


t = int(input())
for loop in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = [arr[0]]
	for i in range(1, n - 1):
		if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:
			ans.append(arr[i])
		elif arr[i] < arr[i - 1] and arr[i] < arr[i + 1]:
			ans.append(arr[i])
	ans.append(arr[n - 1])
	print(len(ans))
	for i in ans:
		print(i, end=' ')
	print()


def answer(n, A):
	l = [A[0]]
	flag = 0
	for i in range(1, n):
		if A[i] - A[i - 1] > 0:
			if flag == 1:
				l.append(A[i - 1])
			flag = 2
		else:
			if flag == 2:
				l.append(A[i - 1])
			flag = 1
	if l[-1] != A[-1]:
		l.append(A[-1])
	print(len(l))
	print(*l)
	return
t = int(input())
for i in range(t):
	n = int(input())
	A = list(map(int, input().split()))
	answer(n, A)


import sys
buff_readline = sys.stdin.readline
readline = sys.stdin.readline
INF = 2 ** 62 - 1

def read_int():
	return int(buff_readline())

def read_int_n():
	return list(map(int, buff_readline().split()))

def read_float():
	return float(buff_readline())

def read_float_n():
	return list(map(float, buff_readline().split()))

def read_str():
	return readline().strip()

def read_str_n():
	return readline().strip().split()

def error_print(*args):
	print(*args, file=sys.stderr)

def mt(f):
	import time

	def wrap(*args, **kwargs):
		s = time.time()
		ret = f(*args, **kwargs)
		e = time.time()
		error_print(e - s, 'sec')
		return ret
	return wrap

def slv(N, A):
	ans = [A[0], A[1]]
	for i in range(2, N):
		if ans[-2] > ans[-1] > A[i]:
			ans.pop()
		elif ans[-2] < ans[-1] < A[i]:
			ans.pop()
		ans.append(A[i])
	print(len(ans))
	print(*ans)

def main():
	T = read_int()
	for _ in range(T):
		N = read_int()
		P = read_int_n()
		slv(N, P)
main()


for i in range(int(input())):
	a = int(input())
	b = list(map(int, input().split()))
	g = b[0] - b[1]
	ans = [b[0]]
	for i2 in range(1, a - 1):
		if g + (b[i2] - b[i2 + 1]) < b[i2] - b[i2 + 1] and b[i2] - b[i2 + 1] > 0 or (g + (b[i2] - b[i2 + 1]) > b[i2] - b[i2 + 1] and b[i2] - b[i2 + 1] < 0):
			ans.append(b[i2])
		g = b[i2] - b[i2 + 1]
	ans.append(b[-1])
	print(len(ans))
	print(*ans)


import math
import collections
from sys import stdin, stdout, setrecursionlimit
from bisect import bisect_left as bsl
from bisect import bisect_right as bsr
import heapq as hq
setrecursionlimit(2 ** 20)
t = 1
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().rstrip().split()))
	cur = 'g' if a[1] > a[0] else 'l'
	l = [a[0]]
	for i in range(1, n - 1):
		if a[i + 1] > a[i]:
			tmp = 'g'
		else:
			tmp = 'l'
		if cur != tmp:
			l.append(a[i])
		cur = tmp
	l.append(a[n - 1])
	print(len(l))
	for i in l:
		print(i, end=' ')
	print()


from collections import deque
test = int(input())
while test > 0:
	test -= 1
	n = int(input())
	a = list(map(int, input().split()))
	mx = 0
	for i in range(n):
		if a[i] == n:
			mx = i
			break
	ans = deque()
	ans.append(a[0])
	i = int(1)
	while i < n:
		if a[i] > a[i - 1]:
			while i < n - 1 and a[i + 1] > a[i]:
				i += 1
		else:
			while i < n - 1 and a[i + 1] < a[i]:
				i += 1
		ans.append(a[i])
		i += 1
	ans = list(ans)
	print(len(ans))
	print(*ans)


def main():
	n = int(input())
	for x in range(n):
		func(int(input()))

def func(n):
	lst = list(map(int, input().split()))
	result = []
	flag = 0
	result.append(lst[0])
	for i in range(n - 1):
		if i == 0:
			flag = -1 if lst[i] > lst[i + 1] else 1
			continue
		if lst[i] > lst[i + 1] and flag == 1:
			result.append(lst[i])
			flag = -1
		elif lst[i] < lst[i + 1] and flag == -1:
			result.append(lst[i])
			flag = 1
	result.append(lst[n - 1])
	print(len(result))
	print(*result)
main()


t = int(input())
for _ in range(t):
	n = int(input())
	p = [int(s) for s in input().split()]
	ans = [p[0]]
	for i in range(1, n - 1):
		if p[i] > p[i - 1] and p[i] > p[i + 1]:
			ans.append(p[i])
		elif p[i] < p[i - 1] and p[i] < p[i + 1]:
			ans.append(p[i])
	ans.append(p[-1])
	print(len(ans))
	print(*ans)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import ceil, floor, gcd, sqrt, trunc, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
mod = pow(10, 9) + 7
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(int(data())):
	n = int(data())
	arr = l()
	if len(arr) == 2:
		out(2)
		out(*arr)
		continue
	answer = [arr[0]]
	sign = -1
	for i in range(1, n):
		if arr[i] > arr[i - 1]:
			if sign == 0:
				answer.append(arr[i - 1])
			sign = 1
		else:
			if sign == 1:
				answer.append(arr[i - 1])
			sign = 0
	answer.append(arr[-1])
	out(len(answer))
	out(*answer)


import sys
input = sys.stdin.readline
for nt in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if n == 2:
		print(2)
		print(*a)
		continue
	ans = [a[0]]
	if a[1] > a[0]:
		turn = 1
	else:
		turn = 0
	s = abs(a[1] - a[0])
	for i in range(2, n):
		if turn:
			if a[i] > a[i - 1]:
				continue
			ans.append(a[i - 1])
			turn = 0
		else:
			if a[i] < a[i - 1]:
				continue
			ans.append(a[i - 1])
			turn = 1
	ans.append(a[-1])
	print(len(ans))
	print(*ans)


import time, math, bisect, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
pi = 3.141592653589793

def II():
	return int(stdin.readline())

def IO():
	return stdin.readline()

def IP():
	return map(int, stdin.readline().split())

def L():
	return list(map(int, stdin.readline().split()))

def P(x):
	return stdout.write(str(x) + '\n')

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

def lcm(a, b):
	return a * b // gcd(a, b)

def gcd(a, b):
	if a == 0:
		return b
	elif b == 0:
		return a
	if a > b:
		return gcd(a % b, b)
	else:
		return gcd(a, b % a)

def readTree():
	v = int(input())
	adj = [set() for i in range(v + 1)]
	for i in range(v - 1):
		(u1, u2) = In()
		adj[u1].add(u2)
		adj[u2].add(u1)
	return (adj, v)

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def sieve():
	li = [True] * 1000001
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	prime = []
	for i in range(1000001):
		if li[i] == True:
			prime.append(i)
	return prime

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count

def solve():
	n = II()
	p = L()
	diff = []
	for i in range(1, n):
		diff.append(p[i] - p[i - 1])
	li = [p[0]]
	for i in range(n - 2):
		if diff[i] < 0:
			if diff[i + 1] > 0:
				li.append(p[i + 1])
		elif diff[i] > 0:
			if diff[i + 1] < 0:
				li.append(p[i + 1])
	li.append(p[-1])
	print(len(li))
	print(*li)
t = II()
for i in range(t):
	solve()


import sys
input = sys.stdin.readline
import math

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input().strip()
	return list(s[:len(s)])

def invr():
	return map(int, input().strip().split())

def from_file(f):
	return f.readline

def solve(n, P):
	up = P[1] - P[0] > 0
	res = [P[0], P[1]]
	L = 2
	for i in range(2, len(P)):
		cur_up = P[i] > res[-1]
		if up == cur_up:
			res[-1] = P[i]
		else:
			L += 1
			res.append(P[i])
			up = cur_up
	return (L, res)
t = inp()
for _ in range(t):
	n = inp()
	P = inlt()
	(L, res) = solve(n, P)
	print(L)
	print(' '.join(map(str, res)))


import heapq
from collections import *
import math

def solve():
	n = int(input())
	a = [int(i) for i in input().split()]
	ans = [a[0]]
	if a[0] < a[1]:
		f = 0
	else:
		f = 1
	i = 0
	while i < n - 1:
		if f == 0:
			while i < n - 1 and a[i] < a[i + 1]:
				i += 1
			f = 1
			ans.append(a[i])
		else:
			while i < n - 1 and a[i] > a[i + 1]:
				i += 1
			f = 0
			ans.append(a[i])
	print(len(ans))
	print(*ans)
t = int(input())
for _ in range(t):
	solve()


import sys
for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	if n == 2:
		print(2)
		print(*p)
		continue
	v = [1] * n
	v1 = p[0]
	v1i = 0
	v2 = p[1]
	v2i = 1
	i = 2
	while i < n:
		if v1 - v2 <= 0 and v2 - p[i] <= 0 or (v1 - v2 >= 0 and v2 - p[i] >= 0):
			v[v2i] = 0
			v[v1i] = 1
			v2 = p[i]
			v2i = i
			i += 1
		else:
			v1 = v2
			v[v1i] = 1
			v[v2i] = 1
			v1i = v2i
			v2 = p[i]
			v2i = i
			i += 1
	su = sum(v)
	print(su)
	arr = [0] * su
	c = 0
	for i in range(0, n):
		if v[i] == 1:
			arr[c] = p[i]
			c += 1
	print(*arr)


t = int(input())
for i in range(t):
	n = int(input())
	aa = list(map(int, input().split()))
	bb = aa.copy()
	if n == 2:
		print(2)
		for a in aa:
			print(a, end=' ')
		continue
	k = 0
	while k < len(aa) - 2:
		(x, y, z) = aa[k:k + 3]
		while x > y > z or x < y < z:
			del aa[k + 1]
			if k >= len(aa) - 2:
				break
			(x, y, z) = aa[k:k + 3]
		k += 1
	print(len(aa))
	for a in aa:
		print(a, end=' ')


from sys import stdin
input = stdin.readline
import bisect
import math
for xoxo in range(1):
	for _ in range(int(input())):
		n = int(input())
		a = list(map(int, input().split()))
		ans = [a[0]]
		b = []
		for i in range(1, n):
			b.append(a[i] - a[i - 1])
		for i in range(n - 2):
			if b[i] > 0 and b[i + 1] > 0 or (b[i] < 0 and b[i + 1] < 0):
				continue
			else:
				ans.append(a[i + 1])
		ans.append(a[-1])
		print(len(ans))
		print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	if a[0] > a[1]:
		fl = 1
	else:
		fl = 0
	ans = [a[0]]
	for i in range(1, n):
		if a[i - 1] > a[i]:
			if fl == 1:
				pass
			else:
				ans.append(a[i - 1])
				fl = 1
		elif fl == 1:
			ans.append(a[i - 1])
			fl = 0
		else:
			pass
	if ans[-1] != a[-1]:
		ans.append(a[-1])
	print(len(ans))
	print(*ans)


import sys
input = sys.stdin.readline
from collections import defaultdict
for _ in range(int(input())):
	N = int(input())
	L = list(map(int, input().split()))
	i = 0
	ans = []
	while i < N - 1:
		if L[i] < L[i + 1]:
			ans.append(L[i])
			while i < N - 1 and L[i] < L[i + 1]:
				i += 1
		else:
			ans.append(L[i])
			while i < N - 1 and L[i] > L[i + 1]:
				i += 1
	if ans[-1] != L[N - 1]:
		ans.append(L[N - 1])
	print(len(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	l1 = list(map(int, input().split()))
	l2 = []
	for i in range(1, n - 1):
		if l1[i + 1] >= l1[i] and l1[i] >= l1[i - 1] or (l1[i + 1] <= l1[i] and l1[i] <= l1[i - 1]):
			l1[i] = l1[i - 1]
		else:
			l2.append(l1[i])
	print(len(l2) + 2)
	print(l1[0], *l2, l1[-1])


for i in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	l = []
	if p[1] > p[0]:
		g = 0
	else:
		g = 1
	for j in range(1, n):
		if p[j] > p[j - 1]:
			s = 1
		else:
			s = 0
		if s != g:
			l.append(p[j - 1])
		g = s
	l.append(p[n - 1])
	print(len(l))
	print(' '.join((str(x) for x in l)))


import os
import sys
from io import BytesIO, IOBase

def main():
	for t in range(int(input())):
		n = int(input())
		l = [int(j) for j in input().split()]
		tmp = 0
		if l[0] > l[1]:
			tmp = -1
		elif l[1] > l[0]:
			tmp = 1
		last = tmp
		arr = [l[0]]
		for i in range(1, n - 1):
			tmp = 0
			if l[i] > l[i + 1]:
				tmp = -1
			elif l[i + 1] > l[i]:
				tmp = 1
			if tmp != last:
				arr.append(l[i])
			last = tmp
		arr.append(l[-1])
		print(len(arr))
		print(' '.join(map(str, arr)))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(t,) = I()
for _ in range(t):
	(n,) = I()
	l = I()
	an = [l[0], l[1]]
	p = 1 if l[0] < l[1] else 2
	for i in range(2, n):
		x = 1 if l[i - 1] < l[i] else 2
		if p != x:
			an.append(l[i])
		else:
			an[-1] = l[i]
		p = x
	print(len(an))
	print(*an)


for i in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	if n == 2:
		print(2)
		print(*arr)
	else:
		cnt = 1
		i = 0
		j = 2
		k = 1
		while True:
			if abs(arr[i] - arr[k]) + abs(arr[k] - arr[j]) == abs(arr[i] - arr[j]):
				arr[k] = -1
				k += 1
				j += 1
			else:
				i = k
				k += 1
				j += 1
			if k == n - 1:
				break
		result = []
		for i in arr:
			if i != -1:
				result.append(i)
		print(len(result))
		print(*result)


tests = int(input())
for i in range(tests):
	n = int(input())
	line = [int(j) for j in input().split(' ')]
	count = 2
	result = [line[0], line[1]]
	if line[0] > line[1]:
		direction = 1
	else:
		direction = -1
	for j in range(2, n):
		if line[j - 1] > line[j]:
			if direction == 1:
				result[count - 1] = line[j]
			else:
				direction = 1
				result.append(line[j])
				count += 1
		elif direction == -1:
			result[count - 1] = line[j]
		else:
			direction = -1
			result.append(line[j])
			count += 1
	print(count)
	for j in range(len(result) - 1):
		print(result[j], end=' ')
	print(result[-1])


from sys import stdin
for _ in range(int(stdin.readline())):
	n = int(stdin.readline())
	arr = list(map(int, stdin.readline().split()))
	ans = [arr[0]]
	for i in range(1, n - 1):
		if ans[-1] > arr[i] and arr[i] > arr[i + 1] or (ans[-1] < arr[i] and arr[i] < arr[i + 1]):
			pass
		else:
			ans.append(arr[i])
	ans.append(arr[n - 1])
	print(len(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	var = 1
	var = 2
	if arr[0] < arr[1]:
		var = 1
	else:
		var = 2
	ans = []
	ans.append(arr[0])
	for i in range(1, n - 1):
		if arr[i - 1] < arr[i] and arr[i + 1] < arr[i]:
			ans.append(arr[i])
		elif arr[i - 1] > arr[i] and arr[i + 1] > arr[i]:
			ans.append(arr[i])
	ans.append(arr[n - 1])
	print(len(ans))
	for i in ans:
		print(i, end=' ')
	print()


t = int(input())
for i in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	a = []
	l = p[0]
	for i in range(1, n - 1):
		if l < p[i] < p[i + 1] or p[i + 1] < p[i] < l:
			continue
		a.append(p[i])
		l = p[i]
	print(2 + len(a))
	print(p[0], *a, p[-1])


from sys import stdin
input = stdin.buffer.readline
for _ in range(int(input())):
	n = int(input())
	(*a,) = map(int, input().split())
	c = a[0] < a[1]
	ans = [a[0]]
	for i in range(n - 1):
		if c and a[i + 1] < a[i] or (not c and a[i + 1] > a[i]):
			ans.append(a[i])
			c ^= 1
	ans.append(a[-1])
	print(len(ans), *ans)


import sys, os, io

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
import math as mt

def main():
	tc = ri()
	for _ in range(tc):
		n = ri()
		p = ria()
		ans = []
		ans.append(p[0])
		for i in range(1, n - 1):
			if p[i] < p[i - 1] and p[i] < p[i + 1] or (p[i] > p[i - 1] and p[i] > p[i + 1]):
				ans.append(p[i])
		ans.append(p[n - 1])
		wi(len(ans))
		wia(ans)

class FastReader(io.IOBase):
	newlines = 0

	def __init__(self, fd, chunk_size=1024 * 8):
		self._fd = fd
		self._chunk_size = chunk_size
		self.buffer = io.BytesIO()

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self, size=-1):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, self._chunk_size if size == -1 else size))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

class FastWriter(io.IOBase):

	def __init__(self, fd):
		self._fd = fd
		self.buffer = io.BytesIO()
		self.write = self.buffer.write

	def flush(self):
		os.write(self._fd, self.buffer.getvalue())
		(self.buffer.truncate(0), self.buffer.seek(0))

class FastStdin(io.IOBase):

	def __init__(self, fd=0):
		self.buffer = FastReader(fd)
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

class FastStdout(io.IOBase):

	def __init__(self, fd=1):
		self.buffer = FastWriter(fd)
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.flush = self.buffer.flush
sys.stdin = FastStdin()
sys.stdout = FastStdout()
main()


for t in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	res = 0
	arr2 = [arr[0]]
	for i in range(1, n - 1):
		if arr[i] >= arr[i + 1] and arr[i - 1] >= arr[i] or (arr[i] <= arr[i + 1] and arr[i - 1] <= arr[i]):
			continue
		else:
			arr2 += [arr[i]]
	arr2 += [arr[-1]]
	print(len(arr2))
	for i in range(len(arr2)):
		print(arr2[i], end=' ')
	print()


from collections import Counter as C, defaultdict as D, deque as Q
from operator import itemgetter as I
from itertools import product as P
from bisect import bisect_left as BL, bisect_right as BR
from heapq import heappush as HPUSH, heappop as HPOP
from math import floor as MF, ceil as MC, gcd as MG, factorial as F, sqrt as SQRT, inf as INFINITY

def player1():
	print('')

def player2():
	print('')

def isPrime(n):
	for i in range(2, MC(SQRT(n)) + 1):
		if n % i == 0:
			return False
	return True

def main():
	for _ in range(int(input())):
		n = int(input())
		p = list(map(int, input().split()))
		ans = []
		ans.append(p[0])
		for i in range(1, n - 1):
			if p[i] < p[i - 1] and p[i] < p[i + 1]:
				ans.append(p[i])
				continue
			if p[i] > p[i - 1] and p[i] > p[i + 1]:
				ans.append(p[i])
				continue
		ans.append(p[-1])
		print(len(ans))
		print(*ans)
main()


from sys import stdin
inp = lambda : stdin.readline().strip()
t = int(inp())
for _ in range(t):
	n = int(inp())
	a = [int(x) for x in inp().split()]
	ans = []
	ans.append(a[0])
	inc = True
	if a[1] > a[0]:
		inc = True
	else:
		inc = False
	for i in range(1, n):
		if inc and a[i] < a[i - 1]:
			ans.append(a[i - 1])
			inc = False
		if not inc and a[i] > a[i - 1]:
			ans.append(a[i - 1])
			inc = True
	ans.append(a[-1])
	print(len(ans))
	print(*ans)


T = int(input())
for _ in range(T):
	n = int(input())
	p = list(map(int, input().split()))
	x = [p[0]]
	for i in range(n - 2):
		if p[i + 2] - p[i + 1] >= 0 and p[i + 1] - p[i] >= 0:
			continue
		if p[i + 2] - p[i + 1] <= 0 and p[i + 1] - p[i] <= 0:
			continue
		else:
			x.append(p[i + 1])
	x.append(p[n - 1])
	print(len(x))
	print(*x)


for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	lst = []
	for j in range(n):
		if j == 0 or j == n - 1 or (a[j] > a[j - 1]) != (a[j + 1] > a[j]):
			lst.append(a[j])
	print(len(lst))
	print(*lst)


import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	n = mints()
	b = []
	for i in mints():
		b.append(i)
		if len(b) > 2 and (b[-1] > b[-2] and b[-2] > b[-3] or (b[-1] < b[-2] and b[-2] < b[-3])):
			b.pop(len(b) - 2)
	print(len(b))
	print(*b)
for i in range(mint()):
	solve()


t = int(input())
for i in range(t):
	n = int(input())
	lst = list(map(int, input().split()))
	lstf = [lst[0]]
	ind = 0
	while True:
		if ind >= n - 1:
			break
		else:
			ind1 = -1
			for j in range(ind + 1, n):
				if lst[j] >= lst[j - 1] and j + 1 < n and (lst[j] > lst[j + 1]) or (lst[j] <= lst[j - 1] and j + 1 < n and (lst[j] < lst[j + 1])):
					ind1 = j
					break
			if ind1 == -1:
				ind = n - 1
				lstf.append(lst[ind])
			else:
				ind = ind1
				lstf.append(lst[ind])
	if lstf[-1] == lstf[-2]:
		lstf.pop()
	print(len(lstf))
	print(*lstf)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	temp = []
	count = 0
	for i in range(n - 1):
		temp.append(l[i + 1] - l[i])
	ans = []
	flag = 0
	if temp[0] > 0:
		flag = 1
	else:
		flag = 0
	ans.append(l[0])
	count += 1
	flag2 = 0
	for i in range(1, len(temp)):
		if temp[i] >= 0 and flag == 1:
			continue
		elif temp[i] < 0 and flag == 0:
			continue
		else:
			if temp[i] < 0:
				flag = 0
			else:
				flag = 1
			count += 1
			ans.append(l[i])
			if i == n - 1:
				flag2 = 1
	if flag2 == 0:
		count += 1
		ans.append(l[n - 1])
	print(count)
	for i in range(len(ans)):
		print(ans[i], end=' ')
	print()


testn = int(input())
for i in range(testn):
	arr_len = int(input())
	arr = list(map(int, input().split()))
	is_inc = arr[0] <= arr[1]
	res = [arr[0]]
	for i in range(1, len(arr) - 1):
		if is_inc and arr[i] > arr[i + 1]:
			res.append(arr[i])
			is_inc = False
		elif not is_inc and arr[i] < arr[i + 1]:
			res.append(arr[i])
			is_inc = True
	res.append(arr[-1])
	print(len(res))
	for x in res:
		print(x, end=' ')
	print()


import math, sys, bisect
from collections import defaultdict, Counter, deque
from itertools import groupby, accumulate
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
ilele = lambda : map(int, input().split())
alele = lambda : list(map(int, input().split()))

def Y(c):
	print(['NO', 'YES'][c])

def y(c):
	print(['no', 'yes'][c])

def Yy(c):
	print(['No', 'Yes'][c])

def groupSequence(lst):
	res = [[lst[0]]]
	for i in range(1, len(lst)):
		if lst[i - 1] < lst[i]:
			res[-1].append(lst[i])
		else:
			res.append([lst[i]])
	return res
for _ in range(int(input())):
	n = int(input())
	A = alele()
	if n == 2:
		print(n)
		print(*A)
	else:
		i = 0
		x = groupSequence(A)
		Ans = []
		m = len(x)
		for i in range(m):
			if len(x[i]) == 1:
				if i == 0 or i == m - 1:
					Ans.append(x[i][0])
			else:
				Ans.append(x[i][0])
				Ans.append(x[i][-1])
		print(len(Ans))
		print(*Ans)


for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	B = [A[0]]
	for i in range(1, len(A) - 1):
		if not (A[i - 1] < A[i] < A[i + 1] or A[i - 1] > A[i] > A[i + 1]):
			B.append(A[i])
	B.append(A[-1])
	print(len(B))
	print(*B)


MOD = 1000000007
si = lambda : input()
dgl = lambda : list(map(int, input()))
ii = lambda : int(input())
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
for _ in range(ii()):
	n = ii()
	a = il()
	l = 0
	L = 0
	maxa = -100000000
	k = []
	k.append(a[0])
	D = 0
	for i in range(1, n - 1):
		if a[i] < a[i - 1] and a[i] > a[i + 1] or (a[i] > a[i - 1] and a[i] < a[i + 1]):
			P = 0
			continue
		else:
			k.append(a[i])
	k.append(a[n - 1])
	print(len(k))
	print(*k)
	T = 0


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	p = [a[0]]
	for i in range(1, n - 1):
		if min(a[i - 1], a[i], a[i + 1]) == a[i] or max(a[i - 1], a[i], a[i + 1]) == a[i]:
			p.append(a[i])
	p.append(a[-1])
	print(len(p))
	print(*p)


def solve(n, l):
	ans = []
	ans.append(l[0])
	for i in range(1, n - 1):
		if l[i - 1] < l[i] and l[i] > l[i + 1] or (l[i - 1] > l[i] and l[i] < l[i + 1]):
			ans.append(l[i])
	ans.append(l[n - 1])
	print(len(ans))
	for i in range(len(ans)):
		print(ans[i], end=' ')
t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	solve(n, l)


for _ in range(int(input())):
	n = int(input())
	s = list(map(int, input().split()))
	arr = [s[0]]
	for i in range(1, n - 1):
		if s[i] > s[i + 1] and s[i] > s[i - 1] or (s[i] < s[i - 1] and s[i] < s[i + 1]):
			arr.append(s[i])
	arr.append(s[-1])
	print(len(arr))
	print(*arr)


from sys import stdin

def main():
	for s in stdin.read().splitlines()[2::2]:
		(a, b, *l) = map(int, s.split())
		(res, u) = ([a, b], a < b)
		for c in l:
			v = b < c
			if u is v:
				res[-1] = c
			else:
				res.append(c)
			(b, u) = (c, v)
		print(len(res), ' '.join(map(str, res)), sep='\n')
main()


t = int(input())
rez = []
for i in range(t):
	n = int(input())
	r = ''
	k = 2
	s = input().split(' ')
	for j in range(n):
		s[j] = int(s[j])
	r += str(s[0]) + ' '
	for j in range(1, n - 1):
		if s[j - 1] < s[j] and s[j] > s[j + 1] or (s[j - 1] > s[j] and s[j] < s[j + 1]):
			r += str(s[j]) + ' '
			k += 1
	r += str(s[n - 1]) + ' '
	rez.append(k)
	rez.append(r)
for i in range(len(rez)):
	print(rez[i])


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	o = [l[0]]
	i = 1
	while i < len(l) - 1:
		if l[i] > l[i - 1] and l[i] > l[i + 1]:
			o.append(l[i])
		elif l[i] < l[i - 1] and l[i] < l[i + 1]:
			o.append(l[i])
		i = i + 1
	o.append(l[-1])
	print(len(o))
	print(*o)


t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	b = [True] * n
	m = 0
	i = 0
	while i < len(p) - 2:
		if p[i] < p[i + 1] < p[i + 2] or p[i] > p[i + 1] > p[i + 2]:
			m += 1
			b[i + 1] = False
		i += 1
	print(n - m)
	for i in range(n - 1):
		if b[i]:
			print(p[i], end=' ')
	print(p[-1])


y = int(input())
ans = []
for i in range(y):
	n = int(input())
	al = input().split()
	m = list(map(int, al))
	an = []
	an.append(m[0])
	for i in range(1, n - 1):
		if abs(m[i] - m[i + 1]) + abs(m[i] - m[i - 1]) > abs(m[i + 1] - m[i - 1]):
			an.append(m[i])
	an.append(m[-1])
	ans.append(an)
for i in ans:
	print(len(i))
	for j in i:
		print(j, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	ans = [ar[0]]
	for i in range(1, n - 1):
		if ar[i] > ar[i - 1] and ar[i] > ar[i + 1]:
			ans.append(ar[i])
		elif ar[i] < ar[i - 1] and ar[i] < ar[i + 1]:
			ans.append(ar[i])
	ans.append(ar[-1])
	print(len(ans))
	for i in ans:
		print(i, end=' ')
	print('')


t = int(input())
for _ in range(t):
	n1 = int(input())
	a = list(map(int, input().split()))
	g = []
	inc = -1
	c = 0
	n = 0
	for i in range(1, n1):
		if a[i] > a[i - 1]:
			if n > 0:
				g.append(f)
				n = 0
				c = 1
				inc = 0
				f = a[i - 1]
			elif inc == 0:
				c += 1
			elif c == 0:
				inc = 0
				c = 1
				f = a[i - 1]
		elif c > 0:
			g.append(f)
			inc = 1
			c = 0
			n = 1
			inc = 1
			f = a[i - 1]
		elif inc == 1:
			n += 1
		elif n == 0:
			inc = 1
			n = 1
			f = a[i - 1]
	if n == 0 and c >= 1:
		g.append(f)
		g.append(a[i])
	if c == 0 and n >= 1:
		g.append(f)
		g.append(a[i])
	print(len(g))
	print(*g, sep=' ')


t = int(input())
for i in range(t):
	n = int(input())
	p = [-1] + list(map(int, input().split())) + [-1]
	sp = []
	for i in range(1, len(p) - 1):
		if (p[i - 1] == -1 or p[i + 1] == -1) or (p[i] > p[i - 1] and p[i] > p[i + 1]) or (p[i] < p[i - 1] and p[i] < p[i + 1]):
			sp.append(p[i])
	print(len(sp))
	print(*sp)


def main():
	n = int(input())
	a = list(map(int, input().split()))
	arr = []
	ans = []
	for i in range(n):
		if i == 0 or i == n - 1 or (a[i - 1] < a[i]) != (a[i] < a[i + 1]):
			ans.append(a[i])
	print(len(ans))
	for x in ans:
		print(x, end=' ')
	print()
	return

def test():
	t = int(input())
	while t:
		main()
		t -= 1
test()


import math
from collections import defaultdict, Counter, deque
INF = float('inf')

def gcd(a, b):
	while b:
		(a, b) = (b, a % b)
	return a

def primeFactor(n):
	if n % 2 == 0:
		return 2
	i = 3
	while i ** 2 <= n:
		if n % i == 0:
			return i
		i += 1
	return n

def main():
	n = int(input())
	arr = list(map(int, input().split()))
	stack = []
	stack.append(arr[0])
	stack.append(arr[1])
	for i in range(2, n):
		if arr[i] > stack[-1] > stack[-2]:
			stack.pop(-1)
		elif arr[i] < stack[-1] < stack[-2]:
			stack.pop(-1)
		stack.append(arr[i])
	print(len(stack))
	print(*stack)
t = int(input())
for _ in range(t):
	main()


from collections import Counter as ctr
from collections import defaultdict as dd
from sys import stdin, stdout
for t in range(int(stdin.readline().strip())):
	n = int(stdin.readline().strip())
	a = list(map(int, stdin.readline().strip().split()))
	if n == 2:
		print(2)
		print(a[0], a[1])
		continue
	b = [[a[i], True] for i in range(n)]
	k = 0
	for i in range(1, n - 1):
		if a[i - 1] < a[i] < a[i + 1] or a[i - 1] > a[i] > a[i + 1]:
			b[i][1] = False
			k += 1
	print(n - k)
	for i in range(n):
		if b[i][1]:
			print(b[i][0], end=' ')
	print()


import sys
import math
from decimal import *

def I():
	return int(sys.stdin.readline())

def IL():
	return list(map(int, sys.stdin.readline().strip().split()))

def ILS():
	return list(map(str, sys.stdin.readline().strip().split()))
tt = I()
for ii in range(tt):
	n = I()
	l = IL()
	ans = []
	ans.append(l[0])
	last = l[1]
	trend = ans[-1] - last
	for i in range(2, len(l)):
		x = l[i]
		if last - x < 0:
			if trend > 0:
				ans.append(last)
			trend = last - x
			last = x
		else:
			if trend < 0:
				ans.append(last)
			trend = last - x
			last = x
	ans.append(last)
	print(len(ans))
	for aa in ans:
		print(aa, end=' ')
	print()
	pass


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(item) for item in input().split()]
	ans = [a[0]]
	for (a1, a2, a3) in zip(a, a[1:], a[2:]):
		if a2 < a1 and a2 < a3:
			ans.append(a2)
		if a2 > a1 and a2 > a3:
			ans.append(a2)
	ans.append(a[-1])
	print(len(ans))
	print(' '.join([str(item) for item in ans]))


T = int(input())
for _ in range(T):
	n = int(input())
	arr = list(map(int, input().split()))
	i = 0
	while True:
		n = len(arr)
		if i < n and i + 1 < n and (i + 2 < n):
			if arr[i] > arr[i + 1] and arr[i + 1] > arr[i + 2]:
				arr.pop(i + 1)
			elif arr[i] < arr[i + 1] and arr[i + 1] < arr[i + 2]:
				arr.pop(i + 1)
			else:
				i += 1
		else:
			break
	print(len(arr))
	print(*arr)


import math
a = int(input())
for i in range(a):
	n = int(input())
	k = [int(x) for x in input().split()]
	change = -1
	newk = k[:]
	while change != 0:
		change = 0
		k = newk[:]
		newk = []
		newk.append(k[0])
		for j in range(1, len(k) - 1):
			if abs(k[j - 1] - k[j]) + abs(k[j] - k[j + 1]) > abs(k[j - 1] - k[j + 1]):
				newk.append(k[j])
			else:
				change += 1
		newk.append(k[-1])
	print(len(newk))
	for i in newk:
		print(i, end=' ')
	print()


for test_case in range(int(input())):
	size = int(input())
	array = list(map(int, input().split()))
	final = []
	for x in range(size):
		if x == 0 or x == size - 1 or (array[x - 1] < array[x]) != (array[x] < array[x + 1]):
			final.append(array[x])
	print(len(final))
	print(*final)


import sys

def gets():
	return sys.stdin.readline().strip()

def get():
	return int(sys.stdin.readline().strip())

def geti():
	return map(int, sys.stdin.readline().strip().split())

def getli():
	return list(map(int, sys.stdin.readline().strip().split()))
for _ in range(get()):
	n = get()
	A = getli()
	v = list(A)
	v1 = [v[0]]
	for i in range(1, n - 1):
		if v[i] > v[i - 1] and v[i] < v[i + 1] or (v[i] < v[i - 1] and v[i] > v[i + 1]):
			continue
		else:
			v1.append(v[i])
	v1.append(v[n - 1])
	print(len(v1))
	for i in v1:
		print(i, end=' ')
	print()


import sys, math, cmath, time
start_time = time.time()

def solve():
	n = inp()
	a = inlt()
	q = [a[0]]
	if a[0] < a[1]:
		qw = 1
	else:
		qw = 0
	if a[-1] < a[-2]:
		a.append(1000000000)
	else:
		a.append(0)
	for i in range(len(a) - 1):
		if qw == 1:
			if a[i + 1] < a[i]:
				q.append(a[i])
				qw = 0
		if qw == 0:
			if a[i + 1] > a[i]:
				q.append(a[i])
				qw = 1
	print(len(q))
	print(*q)

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	t = inp()
	for tt in range(t):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
		sys.stdout.close()

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	return input().strip()

def invr():
	return map(int, input().split())

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
	return q

def power_two(n):
	if n == 1:
		return True
	sttr = str(n)
	len_str = len(sttr)
	sttr = list(sttr)
	num = 0
	if len_str == 1 and sttr[len_str - 1] == '1':
		return False
	while len_str != 1 or sttr[len_str - 1] != '1':
		if (ord(sttr[len_str - 1]) - ord('0')) % 2 == 1:
			return False
		j = 0
		for i in range(len_str):
			num = num * 10 + (ord(sttr[i]) - ord('0'))
			if num < 2:
				if i != 0:
					sttr[j] = '0'
					j += 1
				continue
			sttr[j] = chr(num // 2 + ord('0'))
			j += 1
			num = num - num // 2 * 2
		len_str = j
	return True

def log_two(n):
	return math.log(n) / math.log(2)
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = []
	for i in range(1, n - 1):
		if (a[i - 1] < a[i]) != (a[i] < a[i + 1]):
			ans.append(a[i])
	ans.insert(0, a[0])
	ans.append(a[-1])
	print(len(ans))
	print(*ans)


from math import fabs

def main():
	test = int(input())
	for _ in range(test):
		n = int(input())
		ara = [int(num) for num in input().split()]
		if n == 2:
			ans = ara
		else:
			ans = []
			ans.append(ara[0])
			left = 0
			mid = 1
			right = 2
			while right < n:
				if fabs(ara[left] - ara[mid]) + fabs(ara[mid] - ara[right]) > fabs(ara[left] - ara[right]):
					ans.append(ara[mid])
					left = mid
				mid = right
				right += 1
			ans.append(ara[mid])
		print(len(ans))
		ans = ' '.join(map(str, ans))
		print(ans)
main()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	p = [a[0]]
	i = 0
	while i < n - 2:
		if a[i + 1] > a[i]:
			j = i + 1
			while j < n - 1:
				if a[j + 1] > a[j]:
					j += 1
				else:
					p.append(a[j])
					break
			i = j
		elif a[i + 1] < a[i]:
			k = i + 1
			while k < n - 1:
				if a[k + 1] < a[k]:
					k += 1
				else:
					p.append(a[k])
					break
			i = k
	p.append(a[n - 1])
	print(len(p))
	for x in range(len(p)):
		print(p[x], end=' ')


for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	ans = [a[0]]
	if a[1] > a[0]:
		flag = 1
	else:
		flag = 0
	ref = a[0]
	for i in range(1, n):
		if a[i] > a[i - 1] and flag == 0:
			ans.append(a[i - 1])
			flag = 1
		elif a[i] < a[i - 1] and flag == 1:
			ans.append(a[i - 1])
			flag = 0
	ans.append(a[n - 1])
	print(len(ans))
	print(*ans)


import os
import sys
from io import BytesIO, IOBase
import math

def inputIntArray():
	return list(map(int, input().rstrip().split()))

def inputArray():
	return input().rstrip().split()

def inputVars():
	return map(int, input().rstrip().split())

def inputNum():
	return int(input())

def main():
	for _ in range(inputNum()):
		n = inputNum()
		arr = inputIntArray()
		peaksAndValleys = [arr[0]]
		for pos in range(1, n - 1):
			if arr[pos] < arr[pos - 1] and arr[pos] < arr[pos + 1] or (arr[pos] > arr[pos - 1] and arr[pos] > arr[pos + 1]):
				peaksAndValleys.append(arr[pos])
		peaksAndValleys.append(arr[-1])
		print(len(peaksAndValleys))
		for num in peaksAndValleys:
			print(num, end=' ')
		print(' ')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.readline

def solve():
	n = int(input())
	P = list(map(int, input().split()))
	ret = 2
	ans = [P[0], P[1]]
	now = P[1]
	up = False
	if P[0] < P[1]:
		up = True
	for p in P[2:]:
		if up:
			if now < p:
				ans[-1] = p
				pass
			else:
				up = False
				ret += 1
				ans.append(p)
		elif now > p:
			ans[-1] = p
			pass
		else:
			up = True
			ret += 1
			ans.append(p)
		now = p
	return '\n'.join([str(ret), ' '.join(map(str, ans))])

def main():
	t = int(input())
	ANS = []
	for _ in range(t):
		print(solve())
main()


test = int(input())
while test:
	n = int(input())
	l = input()
	nist = l.split()
	list = []
	for i in nist:
		list.append(int(i))
	nlist = []
	nlist.append(list[0])
	i = 1
	while i < n - 1:
		if (list[i - 1] < list[i]) != (list[i] < list[i + 1]):
			nlist.append(list[i])
		i = i + 1
	nlist.append(list[n - 1])
	print(len(nlist))
	print(*nlist)
	test = test - 1


import sys
input = sys.stdin.buffer.readline

def solution():
	for _ in range(int(input())):
		n = int(input())
		l = list(map(int, input().split()))
		i = 0
		j = 0
		ans = []
		while i < n - 1:
			if l[i + 1] > l[i]:
				while i < n - 1 and l[i + 1] > l[i]:
					i += 1
				ans.append(l[j])
				j = i
			else:
				while i < n - 1 and l[i + 1] < l[i]:
					i += 1
				ans.append(l[j])
				j = i
		ans.append(l[j])
		print(len(ans))
		print(*ans)
solution()


from collections import Counter
import math
from collections import Counter
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	if n == 2:
		print(2)
		print(*arr)
	else:
		v = [False] * n
		v[0] = True
		v[-1] = True
		i = 1
		while i < n - 1:
			var = abs(arr[i - 1] - arr[i]) + abs(arr[i] - arr[i + 1])
			if var <= abs(arr[i - 1] - arr[i + 1]):
				pass
			else:
				v[i] = True
			i += 1
		print(v.count(True))
		for j in range(n):
			if v[j] == True:
				print(arr[j], end=' ')
		print()


import os
import sys
from io import BytesIO, IOBase
profile = 0
pypy = 1

def iin():
	return int(input())

def lin():
	return list(map(int, input().split()))

def get_min(a, b):
	(v1, c1) = a
	(v2, c2) = b
	if v1 < v2:
		return b
	elif v1 > v2:
		return a
	elif c1 < c2:
		return a
	else:
		return b

def main():
	t = iin()
	while t:
		t -= 1
		n = iin()
		a = lin()
		sol = [a[0]]
		for i in range(1, n - 1):
			if sol[-1] <= a[i] <= a[i + 1] or sol[-1] >= a[i] >= a[i + 1]:
				continue
			sol.append(a[i])
		sol.append(a[-1])
		print(len(sol))
		print(*sol)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
if pypy:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')
if profile:
	import cProfile
	cProfile.run('main()')
else:
	main()


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	b = a[:1]
	for i in range(2, n):
		if a[i - 2] <= a[i - 1] and a[i - 1] >= a[i]:
			b.append(a[i - 1])
		elif a[i - 2] >= a[i - 1] and a[i - 1] <= a[i]:
			b.append(a[i - 1])
	b.append(a[-1])
	n = len(b)
	c = b[:1]
	for i in range(1, n):
		if b[i] != b[i - 1]:
			c.append(b[i])
	print(len(c))
	print(' '.join([str(i) for i in c]))


import sys
import math
import collections
import operator as op
from collections import deque
from math import gcd
from functools import reduce
from sys import stdin, stdout, setrecursionlimit
setrecursionlimit(2 ** 20)

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer // denom

def isPowerOfTwo(x):
	return x and (not x & x - 1)

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
T = 1
T = int(stdin.readline())
for _ in range(T):
	n = int(stdin.readline())
	p = list(map(int, stdin.readline().split()))
	ans = [p[0]]
	for i in range(1, n - 1):
		if p[i] > p[i + 1] and p[i] > p[i - 1]:
			ans.append(p[i])
		elif p[i] < p[i + 1] and p[i] < p[i - 1]:
			ans.append(p[i])
	ans.append(p[-1])
	print(len(ans))
	print(*ans)


def main():
	t = int(input())
	for __ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		sub = [a[0]]
		k = 1
		i = 1
		while i < n - 1:
			if abs(sub[-1] - a[i]) + abs(a[i] - a[i + 1]) > abs(sub[-1] - a[i + 1]):
				sub.append(a[i])
				k += 1
			i += 1
		sub.append(a[-1])
		k += 1
		print(k)
		print(*sub)
main()


import sys
from os import path
if path.exists('C:/Users/prana/Desktop/sublime/input.txt'):
	sys.stdin = open('C:/Users/prana/Desktop/sublime/input.txt', 'r')
	sys.stdout = open('C:/Users/prana/Desktop/sublime/output.txt', 'w')

def solve():
	n = int(input())
	p = list(map(int, input().split()))
	ans = []
	if n > 2:
		for i in range(n):
			if i == n - 1 or i == 0 or (p[i - 1] < p[i]) != (p[i] < p[i + 1]):
				ans.append(p[i])
		print(len(ans))
		for i in ans:
			print(i, end=' ')
		print(end='\n')
	else:
		print(2)
		for i in p:
			print(i, end=' ')
		print(end='\n')
T = 1
T = int(input())
for _ in range(1, T + 1):
	print('Case #', _, file=sys.stderr)
	solve()


from sys import stdin, gettrace
from math import copysign
if gettrace():
	inputi = input
else:

	def input():
		return next(stdin)[:-1]

	def inputi():
		return stdin.buffer.readline()

def main():

	def solve():
		n = int(inputi())
		pp = [int(a) for a in inputi().split()]
		ss = [pp[0]]
		for i in range(1, n - 1):
			if pp[i] == ss[-1]:
				continue
			if (pp[i] - ss[-1]) * (pp[i + 1] - pp[i]) < 0:
				ss.append(pp[i])
		if pp[n - 1] != ss[-1]:
			ss.append(pp[n - 1])
		print(len(ss))
		print(' '.join(map(str, ss)))
	t = int(inputi())
	for _ in range(t):
		solve()
main()


for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	if lis[0] > lis[1]:
		f = 0
	else:
		f = 1
	res = [lis[0]]
	for i in range(1, n):
		x = 0
		if f == 0:
			if lis[i] < lis[i - 1]:
				continue
			f = 1
			res.append(lis[i - 1])
			x = 1
		else:
			if lis[i] > lis[i - 1]:
				continue
			f = 0
			res.append(lis[i - 1])
			x = 1
	res.append(lis[-1])
	print(len(res))
	print(*res)


for iiioi in range(int(input())):
	input()
	l = list(map(int, input().split()))
	ans = [l[0]]
	inc = (True, False)[l[0] > l[1]]
	num = l[1]
	for i in range(0, len(l) - 1):
		if inc ^ (l[i + 1] > num) and num != l[i + 1]:
			ans.append(l[i])
			inc = not inc
		num = l[i + 1]
	if ans[-1] != l[-1]:
		ans.append(l[-1])
	print(len(ans))
	print(*ans)


from sys import stdin, stdout
nmbr = lambda : int(stdin.readline())
lst = lambda : list(map(int, stdin.readline().split()))
for _ in range(nmbr()):
	n = nmbr()
	a = lst()
	ans = [a[0], a[1]]
	for i in range(2, n):
		if a[i] > ans[-1] and ans[-1] > ans[-2]:
			ans.pop()
		if a[i] < ans[-1] and ans[-1] < ans[-2]:
			ans.pop()
		ans += [a[i]]
	print(len(ans))
	print(*ans)


from fractions import Fraction
import sys
import bisect
import heapq
from math import *
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
mod = 1000000007

def inp():
	return sys.stdin.readline().strip()

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def graph(vertex):
	return [[] for i in range(0, vertex + 1)]

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for p in range(t):
		solve()

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(a, b):
	ans = 1
	while b > 0:
		if b % 2 == 1:
			ans *= a
		a *= a
		b //= 2
	return ans

def solve():
	n = int(inp())
	a = lis()
	ans = [a[0]]
	help = 0
	i = 1
	while i < len(a) - 1:
		if abs(a[i] - ans[help]) + abs(a[i + 1] - a[i]) <= abs(a[i + 1] - ans[help]):
			i += 1
		else:
			ans.append(a[i])
			help += 1
			i += 1
	ans.append(a[len(a) - 1])
	print(len(ans))
	print(*ans)
testcase(int(inp()))


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	arr = [l[0]]
	for i in range(n - 2):
		d1 = l[i + 1] - l[i]
		d2 = l[i + 2] - l[i + 1]
		if d1 * d2 < 0:
			arr.append(l[i + 1])
	arr.append(l[-1])
	print(len(arr))
	print(*arr)


import queue
import math
t = int(input())
while t:
	n = int(input())
	a = list(map(int, input().split()))
	prev = a[0]
	start = a[0]
	seq1 = []
	for i in range(1, n):
		if a[i] < prev:
			if start != prev:
				seq1.append(start)
				seq1.append(prev)
			start = a[i]
		prev = a[i]
	if start != prev:
		seq1.append(start)
	seq1.append(prev)
	ans1 = 0
	for i in range(len(seq1) - 1):
		ans1 += abs(seq1[i] - seq1[i + 1])
	prev = a[0]
	start = a[0]
	seq2 = []
	for i in range(1, n):
		if a[i] > prev:
			if start != prev:
				seq2.append(start)
				seq2.append(prev)
			start = a[i]
		prev = a[i]
	if start != prev:
		seq2.append(start)
	seq2.append(prev)
	ans2 = 0
	for i in range(len(seq2) - 1):
		ans2 += abs(seq2[i] - seq2[i + 1])
	if ans1 > ans2:
		seq = seq1
	elif ans1 < ans2:
		seq = seq2
	elif len(seq1) < len(seq2):
		seq = seq1
	else:
		seq = seq2
	print(len(seq))
	for x in seq:
		print(x, end=' ')
	print()
	t -= 1


import sys
from sys import stdin
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	arr = [int(j) for j in input().split()]
	res = []
	res.append(arr[0])
	count = 0
	for i in range(1, n - 1):
		if arr[i - 1] < arr[i] and arr[i] > arr[i + 1] or (arr[i - 1] > arr[i] and arr[i] < arr[i + 1]):
			res.append(arr[i])
	res.append(arr[-1])
	print(len(res))
	print(*res)


import math, sys
t = int(input())
while t != 0:
	t -= 1
	n = int(input())
	p = list(map(int, input().split()))
	ans = []
	for i in range(n):
		if i == 0 or i == n - 1 or (p[i - 1] < p[i]) != (p[i] < p[i + 1]):
			ans.append(p[i])
	print(len(ans))
	print(' '.join(map(str, ans)))


import sys

def answer(n, p):
	ans = [p[0]]
	if p[1] > p[0]:
		asc = True
	else:
		asc = False
	for i in range(1, n):
		if asc and p[i - 1] > p[i]:
			asc = False
			ans.append(p[i - 1])
		elif not asc and p[i - 1] < p[i]:
			asc = True
			ans.append(p[i - 1])
	ans.append(p[-1])
	print(len(ans))
	print(' '.join(map(str, ans)))
	return

def main():
	t = int(input())
	while t:
		n = int(sys.stdin.readline())
		p = [int(i) for i in sys.stdin.readline().split()]
		answer(n, p)
		t -= 1
	return
main()


import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	x = int(input())
	l = list(map(int, input().split()))
	last = [l[0]]
	for j in range(1, len(l) - 1):
		if l[j] > l[j - 1] and l[j] > l[j + 1]:
			last.append(l[j])
		if l[j] < l[j - 1] and l[j] < l[j + 1]:
			last.append(l[j])
	if len(last) == 1:
		last.append(l[-1])
	else:
		if last[-1] > last[-2]:
			if l[-1] > last[-1]:
				last[-1] = l[-1]
			if l[-1] < last[-1]:
				last.append(l[-1])
		if last[-1] < last[-2]:
			if l[-1] < last[-1]:
				last[-1] = l[-1]
			if l[-1] > last[-1]:
				last.append(l[-1])
	print(len(last))
	print(*last)


T = int(input().strip())
for t in range(T):
	n = int(input().strip())
	s = list(map(int, input().strip().split()))[:n]
	res = [s[0]]
	for j in range(1, n - 1):
		if s[j - 1] < s[j] < s[j + 1] or s[j - 1] > s[j] > s[j + 1]:
			continue
		res.append(s[j])
	res.append(s[n - 1])
	print(len(res))
	print(*res)


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	d = []
	d.append(l[0])
	for j in range(1, n - 1):
		if l[j] > l[j - 1] and l[j] < l[j + 1]:
			continue
		elif l[j] < l[j - 1] and l[j] > l[j + 1]:
			continue
		else:
			d.append(l[j])
	d.append(l[n - 1])
	print(len(d))
	for j in range(len(d)):
		print(d[j], end=' ')
	print()


import sys
import math
from math import factorial as f
from collections import defaultdict as dd
mod = 1000000007
T = 1
T = int(sys.stdin.readline())
for _ in range(T):
	n = int(input())
	l = list(map(int, input().split()))
	ans = [l[0]]
	for i in range(1, n - 1):
		if l[i] < l[i - 1] and l[i] < l[i + 1]:
			ans.append(l[i])
		if l[i] > l[i - 1] and l[i] > l[i + 1]:
			ans.append(l[i])
	ans.append(l[-1])
	print(len(ans))
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	res = [arr[0]]
	res_len = 2
	ans = 0
	for i in range(1, n - 1):
		if arr[i + 1] > arr[i] and arr[i - 1] > arr[i]:
			res.append(arr[i])
			res_len += 1
		elif arr[i + 1] < arr[i] and arr[i - 1] < arr[i]:
			res.append(arr[i])
			res_len += 1
	res.append(arr[-1])
	print(res_len)
	for i in res:
		print(i, end=' ')
	print()


from fractions import Fraction
import bisect
import os
import io
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq as hq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
from queue import Queue

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def tinput():
	return input().split()

def rinput():
	return map(int, tinput())

def rlinput():
	return list(rinput())
mod = int(1000000000.0) + 7

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
t = 1
t = iinput()
for _ in range(t):
	n = iinput()
	a = rlinput()
	d = defaultdict(int)
	for i in range(n):
		d[a[i]] = i
	ans = [a[0]]
	i = 1
	while i < n:
		j = i
		while j < n and a[j] > a[j - 1]:
			j += 1
		if i != j and j < n:
			ans.append(a[j - 1])
		elif j == n:
			ans.append(a[j - 1])
		k = j
		while k < n and a[k] < a[k - 1]:
			k += 1
		if j != k and k < n:
			ans.append(a[k - 1])
		elif k == n and j != n:
			ans.append(a[k - 1])
		i = k
	print(len(ans))
	print(*ans)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	res = [p[0]]
	inc = True
	prev = p[0]
	if p[0] > p[1]:
		inc = False
	for i in range(1, n):
		if inc and prev > p[i]:
			res.append(prev)
			inc = False
		if not inc and prev < p[i]:
			res.append(prev)
			inc = True
		prev = p[i]
	res.append(p[n - 1])
	print(len(res))
	print(*res)


def rle(arr):
	rle = []
	for i in arr:
		if len(rle) == 0:
			rle.append([i, 1])
		elif rle[-1][0] == i:
			rle[-1][1] += 1
		else:
			rle.append([i, 1])
	return rle

def solve():
	n = input()
	a = [int(x) for x in input().split()]
	diff = [1 if x > y else -1 for (x, y) in zip(a[1:], a[:-1])]
	diff = rle(diff)
	finalarr = [str(a[0])]
	index = 0
	for (_, group) in diff:
		index += group
		finalarr.append(str(a[index]))
	assert index == len(a) - 1
	print(len(finalarr))
	print(' '.join(finalarr))
	return

def main():
	t = int(input())
	for _ in range(t):
		solve()
	return
main()


from __future__ import division, print_function
import itertools
import sys
import os
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	input = raw_input
	range = xrange
	filter = itertools.ifilter
	map = itertools.imap
	zip = itertools.izip

def is_it_local():
	script_dir = str(os.getcwd()).split('/')
	username = 'dipta007'
	return username in script_dir

def READ(fileName):
	if is_it_local():
		sys.stdin = open(f'./{fileName}', 'r')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
if not is_it_local():
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')

def input1(type=int):
	return type(input())

def input2(type=int):
	[a, b] = list(map(type, input().split()))
	return (a, b)

def input3(type=int):
	[a, b, c] = list(map(type, input().split()))
	return (a, b, c)

def input_array(type=int):
	return list(map(type, input().split()))

def input_string():
	s = input()
	return list(s)
if is_it_local():

	def debug(*args):
		st = ''
		for arg in args:
			st += f'{arg} '
		print(st)
else:

	def debug(*args):
		pass
arr = []
n = 0
mp = {}
from collections import deque

def main():
	t = input1()
	for ci in range(t):
		global arr, n, mp
		n = input1()
		arr = input_array()
		res = [arr[i] for i in range(n) if i == 0 or i == n - 1 or arr[i - 1] > arr[i] < arr[i + 1] or (arr[i - 1] < arr[i] > arr[i + 1])]
		print(len(res))
		print(*res)
	pass
main()


for _ in range(0, int(input())):
	n = int(input())
	l = list(map(int, input().strip().split()))
	res = [l[0]]
	curr = l[0]
	for i in range(1, n - 1):
		if l[i] > l[i - 1] and l[i] > l[i + 1] or (l[i] < l[i - 1] and l[i] < l[i + 1]):
			res.append(l[i])
	res.append(l[-1])
	print(len(res))
	print(' '.join((str(x) for x in res)))


t = int(input())
for t1 in range(t):
	n = int(input())
	p = [int(n1) for n1 in input().split()]
	count = 0
	sub = [p[0]]
	while len(p) - 1 > count:
		a = count
		if count == 0:
			diff = p[a + 1] - p[a]
			sub.append(p[a + 1])
			if diff >= 0:
				diff_prev = 'p'
			if diff < 0:
				diff_prev = 'n'
			count = count + 1
		else:
			diff = p[a + 1] - p[a]
			if diff >= 0:
				diff = 'p'
			elif diff < 0:
				diff = 'n'
			else:
				pass
			if diff == diff_prev:
				sub.pop(-1)
				sub.append(p[a + 1])
				diff_prev = diff
			else:
				sub.append(p[a + 1])
				diff_prev = diff
			count = count + 1
	print(len(sub))
	print(*sub, sep=' ')


rw = int(input())
for ewqr in range(rw):
	n = int(input())
	a = list(map(int, input().split()))
	ai = []
	ai.append(0)
	for i in range(1, n - 1):
		if a[i - 1] < a[i] > a[i + 1] or a[i - 1] > a[i] < a[i + 1]:
			ai.append(i)
	ai.append(n - 1)
	print(len(ai))
	for i in ai:
		print(a[i], end=' ')
	print()


import sys
from fractions import gcd
from math import ceil, sqrt, sin, pi, tan
from collections import defaultdict
read = sys.stdin.buffer.readline
import heapq
mi = lambda : map(int, read().split())
li = lambda : list(mi())
cin = lambda : int(read())
for _t in range(cin()):
	n = cin()
	a = li()
	ans = [a[0]]
	for i in range(1, n - 1):
		if a[i] < a[i + 1] and a[i] < a[i - 1]:
			ans.append(a[i])
		elif a[i] > a[i - 1] and a[i] > a[i + 1]:
			ans.append(a[i])
	ans.append(a[-1])
	print(len(ans))
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	a = [*map(int, input().split())]
	ans = [a[0]]
	i = 0
	for i in range(1, n - 1):
		if a[i - 1] < a[i] > a[i + 1] or a[i - 1] > a[i] < a[i + 1]:
			ans += [a[i]]
	ans += [a[-1]]
	print(len(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(i) for i in input().split()]
	inc = True if arr[0] < arr[1] else False
	out = [arr[0]]
	for i in range(2, n):
		if inc and arr[i - 1] > arr[i]:
			out.append(arr[i - 1])
			inc = False
		elif not inc and arr[i - 1] < arr[i]:
			out.append(arr[i - 1])
			inc = True
	out.append(arr[-1])
	print(len(out))
	print(*out)


for _ in range(int(input())):
	n = int(input())
	lis = list(map(int, input().split()))
	ans = n
	tmp = [0] * (n + 3)
	for i in range(1, n - 1):
		if lis[i] >= lis[i - 1] and lis[i] <= lis[i + 1]:
			ans -= 1
			tmp[lis[i]] = -1
		elif lis[i - 1] >= lis[i] and lis[i] >= lis[i + 1]:
			ans -= 1
			tmp[lis[i]] = -1
	print(ans)
	ans = [i for i in lis if tmp[i] != -1]
	print(*ans)


def main():
	for _ in range(int(input())):
		input()
		(a, b, *l) = map(int, input().split())
		(res, u) = ([a, b], a < b)
		for c in l:
			v = b < c
			if u is v:
				res[-1] = c
			else:
				res.append(c)
			(b, u) = (c, v)
		print(len(res), ' '.join(map(str, res)), sep='\n')
main()


import re
import sys
from bisect import bisect, bisect_left, insort, insort_left
from collections import Counter, defaultdict, deque
from copy import deepcopy
from decimal import Decimal
from itertools import accumulate, combinations, combinations_with_replacement, groupby, permutations, product
from math import acos, asin, atan, ceil, cos, degrees, factorial, gcd, hypot, log2, pi, radians, sin, sqrt, tan
from operator import itemgetter, mul
from string import ascii_lowercase, ascii_uppercase, digits

def inp():
	return int(input())

def inlist():
	return list(map(int, input().split()))

def instr():
	s = input()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
t = inp()
for _ in range(t):
	n = inp()
	a = inlist()
	res = []
	res.append(a[0])
	flip = 0
	if a[1] < a[0]:
		flip = 1
	for i in range(1, n):
		if flip == 0 and a[i] < a[i - 1]:
			res.append(a[i - 1])
			flip = 1
		elif flip == 1 and a[i] >= a[i - 1]:
			res.append(a[i - 1])
			flip = 0
	res.append(a[n - 1])
	print(len(res))
	print(*res)


from sys import stdin
input = stdin.readline
for test in range(int(input())):
	n = int(input())
	lst = list(map(int, input().split()))
	(store, arr) = (lst[0], [lst[0]])
	i = 1
	while i < n:
		flag = 0
		while i < n and lst[i] > store:
			flag = 1
			store = lst[i]
			i += 1
		if flag:
			arr.append(store)
		flag = 0
		while i < n and lst[i] < store:
			flag = 1
			store = lst[i]
			i += 1
		if flag:
			arr.append(store)
	print(len(arr))
	print(*arr)


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [str(p[0])]
	for i in range(1, n - 1):
		if p[i - 1] < p[i] < p[i + 1]:
			continue
		if p[i - 1] > p[i] > p[i + 1]:
			continue
		ans.append(str(p[i]))
	ans.append(str(p[-1]))
	print(len(ans))
	print(' '.join(ans))


for t in range(int(input())):
	n = int(input())
	num = list(map(int, input().split()))
	ls = [num[0]]
	for i in range(1, n - 1):
		if num[i - 1] > num[i] < num[i + 1] or num[i - 1] < num[i] > num[i + 1]:
			ls.append(num[i])
	tot = 0
	ls.append(num[-1])
	print(len(ls))
	print(*ls)


t = int(input())
answer = []
for test in range(t):
	n = int(input())
	liste = list(map(int, input().split(' ')))
	local_answer = []
	local_answer.append(str(liste[0]))
	for i in range(1, n - 1):
		if liste[i] > liste[i - 1] and liste[i] > liste[i + 1] or (liste[i] < liste[i - 1] and liste[i] < liste[i + 1]):
			local_answer.append(str(liste[i]))
	local_answer.append(str(liste[-1]))
	string = str(len(local_answer)) + '\n' + ' '.join(local_answer)
	answer.append(string)
print('\n'.join(answer))


def solve():
	n = int(input())
	mas = list(map(int, input().split()))
	ans = []
	for i in range(0, n):
		if i == 0 or i == n - 1:
			ans.append(mas[i])
		elif mas[i] > mas[i - 1] and mas[i + 1] > mas[i]:
			continue
		elif mas[i] < mas[i - 1] and mas[i + 1] < mas[i]:
			continue
		else:
			ans.append(mas[i])
	print(len(ans))
	for i in ans:
		print(i, end=' ')
	print('\n')
t = int(input())
for _ in range(t):
	solve()


def mnm(i):
	k = i + 1
	while k < n:
		if arr[k] > arr[k - 1]:
			return k - 1
		k += 1
	else:
		return k - 1

def mxm(i):
	k = i + 1
	while k < n:
		if arr[k] < arr[k - 1]:
			return k - 1
		k += 1
	else:
		return k - 1
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	temp = [arr[0]]
	i = 0
	while i < n:
		if i == n - 1:
			break
		if arr[i + 1] > arr[i]:
			mx_ind = mxm(i)
			temp.append(arr[mx_ind])
			i = mx_ind
		else:
			mn_ind = mnm(i)
			temp.append(arr[mn_ind])
			i = mn_ind
	print(len(temp))
	print(*temp)


t = int(input())
while t:
	n = int(input())
	a = list(map(int, input().split()))
	d = []
	for i in range(n):
		if i == 0 or i == n - 1 or (a[i - 1] < a[i] and a[i + 1] < a[i]) or (a[i - 1] > a[i] and a[i + 1] > a[i]):
			d.append(str(a[i]))
	print(len(d))
	print(' '.join(d))
	t = t - 1


def ch(a, b, c):
	if a <= b <= c or a >= b >= c:
		return False
	if a <= b >= c or a >= b <= c:
		return True
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	c = 1
	ans = [l[0]]
	for i in range(1, len(l) - 1):
		if l[i - 1] < l[i] > l[i + 1] or l[i - 1] > l[i] < l[i + 1]:
			ans.append(l[i])
			c += 1
	ans.append(l[-1])
	c += 1
	print(c)
	print(*ans)


import os, io
from sys import stdout
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	i = 1
	prev = (0, l[0])
	res = []
	res.append(l[0])
	while i < len(l):
		while i < len(l) and l[i] >= l[i - 1]:
			i += 1
		peak = (i - 1, l[i - 1])
		while i < len(l) and l[i] <= l[i - 1]:
			i += 1
		valley = (i - 1, l[i - 1])
		res.append(peak[1])
		res.append(valley[1])
	res.append(l[-1])
	b = []
	a = set([])
	for e in res:
		if e in a:
			continue
		b.append(e)
		a.add(e)
	print(len(b))
	print(' '.join([str(e) for e in b]))


def sign(x):
	return (x > 0) - (x < 0)
t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	p.append(-sign(p[-1] - p[-2]) * 100000)
	pre = 0
	ans = []
	for i in range(1, n + 1):
		cur = sign(p[i] - p[i - 1])
		if cur == 0:
			continue
		elif cur == pre:
			continue
		else:
			ans.append(p[i - 1])
			pre = cur
	print(len(ans))
	print(' '.join(map(str, ans)))


from collections import defaultdict
from collections import Counter
import sys
input = sys.stdin.readline

def solve(n, p):
	ans = [p[0]]
	ans0 = (p[i] for i in range(1, n - 1) if p[i - 1] < p[i] > p[i + 1] or p[i - 1] > p[i] < p[i + 1])
	ans.extend(ans0)
	ans.append(p[n - 1])
	print(len(ans))
	print(' '.join(map(str, ans)))

def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		p = list(map(int, input().split()))
		solve(n, p)
main()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	k = a[0]
	ans = []
	ans.append(k)
	f = 0
	if a[1] > a[0]:
		f = 1
	for i in range(1, n):
		if a[i] < a[i - 1] and f == 1 or (a[i] > a[i - 1] and f == 0):
			ans.append(a[i - 1])
			k = a[i]
			f = 1 ^ f
	ans.append(a[n - 1])
	print(len(ans))
	for i in ans:
		print(i, end=' ')
	print('')


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [str(a[0])]
	for i in range(1, n - 1):
		if a[i] > a[i - 1] and a[i] > a[i + 1] or (a[i] < a[i - 1] and a[i] < a[i + 1]):
			b.append(str(a[i]))
	b.append(str(a[n - 1]))
	print(len(b))
	print(' '.join(b))


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(var) for var in input().split()]
	(prevIdx, val, toPrint) = (0, 0, [a[0]])
	for i in range(1, n - 1):
		if a[i - 1] < a[i] > a[i + 1]:
			prevIdx = i
			toPrint.append(a[i])
		elif a[i - 1] > a[i] < a[i + 1]:
			prevIdx = i
			toPrint.append(a[i])
	if a[-1] != a[prevIdx]:
		toPrint.append(a[-1])
	print(len(toPrint))
	for var in toPrint:
		print(var, end=' ')
	print()


import os
import sys
from io import BytesIO, IOBase

def readvars():
	k = map(int, input().split())
	return k

def readlist():
	li = list(map(int, input().split()))
	return li

def anslist(li):
	ans = ' '.join([str(v) for v in li])
	return ans

def main():
	t = 1
	t = int(input())
	for xx in range(t):
		n = int(input())
		p = readlist()
		lis = [p[0]]
		for i in range(1, n - 1):
			if p[i] > p[i - 1] and p[i] > p[i + 1]:
				lis.append(p[i])
			elif p[i] < p[i - 1] and p[i] < p[i + 1]:
				lis.append(p[i])
		lis.append(p[n - 1])
		print(len(lis))
		print(anslist(lis))
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


from sys import stdin, exit
input = stdin.readline

def i():
	return input()

def ii():
	return int(input())

def iis():
	return map(int, input().split())

def liis():
	return list(map(int, input().split()))

def print_array(a):
	print(' '.join(map(str, a)))

def calcular(a):
	soma = 0
	for (idx, i) in enumerate(a[:-1]):
		soma += abs(a[idx] - a[idx + 1])
	return soma
t = ii()
for _ in range(t):
	n = ii()
	p = liis()
	a = p[0]
	numbers1 = [a]
	numbers2 = [a]
	last = p[0]
	cresce = True
	for i in p[1:]:
		if cresce:
			if i >= last:
				last = i
			else:
				numbers1.append(last)
				last = i
				cresce = False
		elif i <= last:
			last = i
		elif numbers1[-1] != last:
			numbers1.append(last)
			last = i
			cresce = True
	cresce = False
	last = p[0]
	for i in p[1:]:
		if cresce:
			if i >= last:
				last = i
			else:
				numbers2.append(last)
				last = i
				cresce = False
		elif i <= last:
			last = i
		elif last != numbers2[-1]:
			numbers2.append(last)
			last = i
			cresce = True
	if numbers1[-1] != p[-1]:
		numbers1.append(p[-1])
	if numbers2[-1] != p[-1]:
		numbers2.append(p[-1])
	if calcular(numbers1) > calcular(numbers2):
		print(len(numbers1))
		print_array(numbers1)
	elif calcular(numbers1) == calcular(numbers2):
		if len(numbers1) < len(numbers2):
			print(len(numbers1))
			print_array(numbers1)
		else:
			print(len(numbers2))
			print_array(numbers2)
	else:
		print(len(numbers2))
		print_array(numbers2)


from collections import deque
q = int(input())
for _ in range(q):
	n = int(input())
	A = list(map(int, input().split(' ')))
	temp = A[0]
	if A.count(temp) == n:
		print(2)
		print(temp, temp)
		continue
	(l, r) = (0, 1)
	for i in range(1, n):
		if A[i] == A[i - 1]:
			continue
		elif A[i] > A[i - 1]:
			l = i - 1
			r = i
			inc = True
			break
		else:
			l = i - 1
			r = i
			inc = False
			break
	start = r + 1
	ans = []
	ans.append(A[l])
	for i in range(start, n - 1):
		if inc:
			if A[i] >= A[i - 1]:
				r = i
			else:
				ans.append(A[r])
				l = i - 1
				r = i
				inc = False
		elif A[i] <= A[i - 1]:
			r = i
		else:
			ans.append(A[r])
			l = i - 1
			r = i
			inc = True
	i = n - 1
	if inc:
		if A[i] > A[i - 1]:
			ans.append(A[i])
		if A[i] < A[i - 1]:
			ans.append(A[r])
			ans.append(A[i])
	else:
		if A[i] < A[i - 1]:
			ans.append(A[i])
		if A[i] > A[i - 1]:
			ans.append(A[r])
			ans.append(A[i])
	print(len(ans))
	for i in ans:
		print(i, end=' ')
	print()


def triplSum(a1, a2, a3):
	return abs(a1 - a2) + abs(a2 - a3)

def doublelSum(a1, a2):
	return abs(a1 - a2)
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	s = 0
	i = 0
	i1 = 1
	b = [a[0]]
	while True:
		if i1 + 1 == n - 1:
			if triplSum(a[i], a[i1], a[i1 + 1]) > doublelSum(a[i], a[i1 + 1]):
				s += triplSum(a[i], a[i1], a[i1 + 1])
				b.append(a[i1])
				b.append(a[i1 + 1])
			else:
				s += doublelSum(a[i], a[i1 + 1])
				b.append(a[i1 + 1])
			break
		elif i1 == n - 1:
			if b[-1] == a[i]:
				b.append(a[i1])
			break
		elif triplSum(a[i], a[i1], a[i1 + 1]) > doublelSum(a[i], a[i1 + 1]):
			b.append(a[i1])
			i = i1
			i1 = i + 1
		else:
			i1 += 1
	print(len(b))
	print(*b)


for t in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	count = 2
	lis = []
	lis.append(arr[0])
	for i in range(1, n - 1):
		if arr[i] < arr[i + 1] and arr[i] < arr[i - 1]:
			count += 1
			lis.append(arr[i])
		elif arr[i] > arr[i + 1] and arr[i] > arr[i - 1]:
			count += 1
			lis.append(arr[i])
	lis.append(arr[-1])
	print(count)
	print(*lis)


import sys
input = sys.stdin.readline
answer = []
for kek in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [p[0]]
	flag = True
	if p[1] > p[0]:
		flag = True
	else:
		flag = False
	for i in range(1, n):
		if flag:
			if p[i] > p[i - 1]:
				continue
			else:
				flag = False
				ans.append(p[i - 1])
		elif p[i] < p[i - 1]:
			continue
		else:
			flag = True
			ans.append(p[i - 1])
	if ans[-1] != p[-1]:
		ans.append(p[-1])
	answer.append(ans)
for i in answer:
	print(len(i))
	print(*i)


for _ in range(int(input())):
	n = int(input())
	arr = [int(x) for x in input().split()]
	l = []
	for x in range(1, n - 1):
		if (arr[x] > arr[x + 1]) == (arr[x] > arr[x - 1]):
			l.append(arr[x])
	print(len(l) + 2)
	print(arr[0], *l, arr[-1])


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	p_list = list(map(int, input().split()))
	output = [p_list[0]]
	q = [0]
	for i in range(1, n):
		if p_list[i] > p_list[i - 1]:
			q.append('+')
		else:
			q.append('-')
	for j in range(1, n - 1):
		if q[j] != q[j + 1]:
			output.append(p_list[j])
	output.append(p_list[n - 1])
	print(len(output))
	print(' '.join((str(i) for i in output)))


def solve(n, l):
	x = [str(l[0])]
	if n <= 2:
		x = [str(l[0]), str(l[1])]
		return x
	for i in range(1, n - 1):
		if l[i] > l[i - 1] and l[i] > l[i + 1] or (l[i] < l[i - 1] and l[i] < l[i + 1]):
			x.append(str(l[i]))
	x.append(str(l[n - 1]))
	return x
t = int(input())
for we in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	x = solve(n, l)
	print(len(x))
	print(' '.join(x))


for i in range(int(input())):
	l = input()
	p = [int(i) for i in input().split()]
	r = p[0:1]
	a = p[0]
	great = False
	less = False
	for i in p[1:]:
		if i > a:
			if less:
				r.append(a)
				less = False
			great = True
		else:
			if great:
				r.append(a)
				great = False
			less = True
		a = i
	print(len(r) + 1)
	print(*r, a)


t = int(input())
for case in range(t):
	n = int(input())
	p = [int(x) for x in input().split(' ')]
	dels = set()
	for i in range(1, n - 1):
		if min(p[i - 1], p[i + 1]) < p[i] < max(p[i - 1], p[i + 1]):
			dels.add(i)
	p = [p[i] for i in range(n) if i not in dels]
	print(len(p))
	print(*p)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	k = []
	c = ''
	if l[0] < l[1]:
		c = 'i'
	else:
		c = 'd'
	k.append(l[0])
	k.append(l[1])
	for i in range(1, n - 1):
		if l[i] <= l[i + 1]:
			if c == 'i':
				k[len(k) - 1] = l[i + 1]
			else:
				k.append(l[i + 1])
			c = 'i'
		elif l[i] >= l[i + 1]:
			if c == 'd':
				k[len(k) - 1] = l[i + 1]
			else:
				k.append(l[i + 1])
			c = 'd'
	print(len(k))
	print(' '.join(map(str, k)))


for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	pp = []
	for i in range(1, n - 1):
		if ar[i] < ar[i + 1] and ar[i] < ar[i - 1]:
			pp.append(ar[i])
		if ar[i] > ar[i + 1] and ar[i] > ar[i - 1]:
			pp.append(ar[i])
	print(2 + len(pp))
	print(ar[0], *pp, ar[-1])


cases = int(input())
for i in range(cases):
	l1 = int(input())
	l2 = input().split(' ')
	arr = []
	for j in l2:
		arr.append(int(j))
	ans = []
	index = []
	start = 0
	transition = 0
	inc = False
	dec = False
	while start < len(arr) - 1:
		ele1 = arr[start]
		ele2 = arr[start + 1]
		if transition == 0:
			if ele1 > ele2:
				dec = True
				transition += 1
				index.append(start)
			elif ele2 > ele1:
				inc = True
				transition += 1
				index.append(start)
		elif transition == 1:
			if inc:
				if ele2 < ele1:
					index.append(start)
					dec = True
					inc = False
			elif dec:
				if ele2 > ele1:
					index.append(start)
					inc = True
					dec = False
		start += 1
	if transition == 1:
		if index[-1] != len(arr) - 1:
			index.append(len(arr) - 1)
	for ind in index:
		ans.append(str(arr[ind]))
	print(len(ans))
	print(' '.join(ans))


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	l1 = [int(i) for i in input().split(' ')]
	l2 = []
	k = 1
	flag = 0
	if l1[1] > l1[0]:
		flag = 1
	l2.append(l1[0])
	for i in range(1, n - 1):
		if flag == 1:
			if l1[i + 1] < l1[i]:
				l2.append(l1[i])
				k += 1
				flag = 0
		elif flag == 0:
			if l1[i + 1] > l1[i]:
				l2.append(l1[i])
				k += 1
				flag = 1
	l2.append(l1[-1])
	print(k + 1)
	for i in l2:
		print(i, end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	i = 0
	while i < len(arr) - 2:
		if arr[i] <= arr[i + 1] and arr[i + 1] <= arr[i + 2]:
			del arr[i + 1]
		elif arr[i] >= arr[i + 1] and arr[i + 1] >= arr[i + 2]:
			del arr[i + 1]
		else:
			i += 1
	print(len(arr))
	print(' '.join(map(str, arr)))


import math

def process_test_case(i_t):
	n = int(input())
	p_vec = list(map(int, input().split()))
	first = p_vec[0]
	last = p_vec[-1]
	out_vec = [p_vec[0]]
	i = 0
	j = 1
	while i + j < n:
		i_diff = p_vec[i + 1] - p_vec[i]
		while i + j < n and i_diff * (p_vec[i + j] - p_vec[i + j - 1]) > 0:
			j += 1
		if i + j < n:
			out_vec.append(p_vec[i + j - 1])
			i = i + j - 1
			j = 1
		else:
			out_vec.append(p_vec[-1])
			i = n
	print(len(out_vec))
	print(' '.join([str(x) for x in out_vec]))
	return None
n_tests = int(input())
for i_test in range(1, n_tests + 1):
	process_test_case(i_test)


for _ in range(int(input())):
	n = int(input())
	P = list(map(int, input().split()))
	i = 1
	A = []
	A.append(P[0])
	while i < n - 1:
		if P[i] > P[i - 1] and P[i] > P[i + 1]:
			A.append(P[i])
		elif P[i] < P[i - 1] and P[i] < P[i + 1]:
			A.append(P[i])
		i += 1
	A.append(P[n - 1])
	print(len(A))
	print(*A)


def minSubSeq(seq, n):
	ans = []
	for i in range(0, n):
		if i == 0 or i == n - 1 or (seq[i - 1] < seq[i]) != (seq[i] < seq[i + 1]):
			ans.append(seq[i])
	print(len(ans))
	print(*ans)

def main():
	numOfSets = int(input())
	for _ in range(numOfSets):
		n = int(input())
		seq = list(map(int, input().split()))
		minSubSeq(seq, n)
main()


import math
for q in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	for i in range(n):
		if i == 0 or i == n - 1 or (a[i] > a[i - 1]) != (a[i + 1] > a[i]):
			b.append(a[i])
	print(len(b))
	print(*b)


T = int(input())
for _ in range(T):
	n = int(input())
	a = list(map(int, input().split()))
	d = 1 if a[1] > a[0] else -1
	c = a[1]
	ans = [a[0]]
	for i in range(1, n):
		if d == 1:
			if a[i] > a[i - 1]:
				c = a[i]
			else:
				ans.append(c)
				d = -1
				c = a[i]
		elif a[i] < a[i - 1]:
			c = a[i]
		else:
			ans.append(c)
			d = 1
			c = a[i]
	ans.append(c)
	print(len(ans))
	print(' '.join(map(str, ans)))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	x = [a[0]]
	for i in range(1, n - 1):
		if a[i - 1] < a[i] > a[i + 1] or a[i - 1] > a[i] < a[i + 1]:
			x.append(a[i])
	x.append(a[-1])
	print(len(x))
	print(*x)


from sys import stdin as cin
lmap = lambda f, v: list(map(f, v))

def subarray(a):
	yield a[0]
	for i in range(1, len(a) - 1):
		if a[i - 1] < a[i] > a[i + 1] or a[i - 1] > a[i] < a[i + 1]:
			yield a[i]
	yield a[-1]

def main():
	t = int(next(cin).strip())
	for i in range(t):
		n = lmap(int, next(cin).strip().split())
		a = lmap(int, next(cin).strip().split())
		r = list(subarray(a))
		print(len(r))
		print(' '.join(map(str, r)))
main()


t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	it = 1
	ans = []
	ans.append(arr[0])
	for j in range(1, n - 1, 1):
		if arr[j] > arr[j - 1] and arr[j + 1] < arr[j] or (arr[j] < arr[j - 1] and arr[j + 1] > arr[j]):
			ans.append(arr[j])
	ans.append(arr[len(arr) - 1])
	print(len(ans))
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	v = []
	for i in range(1, n - 1):
		if (p[i] > p[i - 1]) != (p[i] < p[i + 1]):
			v.append(p[i])
	v.insert(0, p[0])
	v.append(p[-1])
	print(len(v))
	print(*v)


def main():
	n = int(input())
	lst = list(map(int, input().split()))
	take = [lst[0]]
	sign = 0
	for i in range(1, n):
		if i == n - 1:
			take.append(lst[i])
		elif lst[i] > take[-1]:
			if lst[i + 1] < lst[i]:
				take.append(lst[i])
		elif lst[i] < take[-1]:
			if lst[i + 1] > lst[i]:
				take.append(lst[i])
	line = str(len(take)) + '\n'
	for i in take:
		line += str(i) + ' '
	print(line)
t = int(input())
for i in range(t):
	main()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	s = []
	ans = 0
	temp = a[0]
	s.append(a[0])
	i = 1
	while i < n:
		if a[i] > temp:
			sel = i
			j = i + 1
			while j < n and a[j] > a[j - 1]:
				sel = j
				j += 1
			ans += a[sel] - temp
			temp = a[sel]
		else:
			sel = i
			j = i + 1
			while j < n and a[j] < a[j - 1]:
				sel = j
				j += 1
			ans += temp - a[sel]
			temp = a[sel]
		s.append(a[sel])
		i = sel + 1
	print(len(s))
	for i in s:
		print(i, end=' ')
	print('')


t = int(input())
while t:
	t -= 1
	n = int(input())
	arr = [int(s) for s in input().split()]
	cur_sum = 0
	for i in range(1, n):
		cur_sum = cur_sum + abs(arr[i] - arr[i - 1])
	removed = [0 for i in range(n)]
	intact = [arr[0]]
	for i in range(1, n - 1):
		x = abs(arr[i] - intact[-1]) + abs(arr[i] - arr[i + 1])
		y = abs(intact[-1] - arr[i + 1])
		if y < x:
			intact.append(arr[i])
	intact.append(arr[n - 1])
	ans = []
	for i in range(n):
		if not removed[i]:
			ans.append(arr[i])
	print(len(intact))
	print(*intact)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
testcases = int(input())
for j in range(testcases):
	n = int(input())
	perms = list(map(int, input().split()))
	changes = [0]
	for s in range(1, n):
		diff = perms[s] - perms[s - 1]
		changes.append(diff)
	outy = [perms[0]]
	if n >= 3:
		for s in range(2, n):
			if changes[s] * changes[s - 1] < 0:
				outy.append(perms[s - 1])
	outy.append(perms[n - 1])
	outy = [str(k) for k in outy]
	print(len(outy))
	print(' '.join(outy))


import sys
input = sys.stdin.readline
for T in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	inc = False
	dec = False
	res = [arr[0]]
	for i in range(1, n):
		if arr[i] < arr[i - 1]:
			if dec:
				res.pop()
			res.append(arr[i])
			dec = True
			inc = False
		elif arr[i] > arr[i - 1]:
			if inc:
				res.pop()
			res.append(arr[i])
			dec = False
			inc = True
	print(len(res))
	print(*res)


from sys import stdin, stdout
import math
from itertools import permutations, combinations
from collections import defaultdict
from collections import Counter
from bisect import bisect_left
import sys
from queue import PriorityQueue
mod = 1000000007

def L():
	return list(map(int, stdin.readline().split()))

def In():
	return map(int, stdin.readline().split())

def I():
	return int(stdin.readline())

def printIn(ob):
	return stdout.write(str(ob) + '\n')

def powerLL(n, p):
	result = 1
	while p:
		if p & 1:
			result = result * n % mod
		p = int(p / 2)
		n = n * n % mod
	return result

def myCode():
	n = I()
	lst = L()
	ans_list = [lst[0]]
	for i in range(1, len(lst) - 1):
		if lst[i - 1] < lst[i] > lst[i + 1] or lst[i - 1] > lst[i] < lst[i + 1]:
			ans_list.append(lst[i])
	ans_list.append(lst[-1])
	print(len(ans_list))
	print(*ans_list)

def main():
	for t in range(I()):
		myCode()
main()


import math
t = int(input())
for _ in range(t):
	n = int(input())
	lst = [1] * (n + 1)
	count = 0
	lst[0] = -1
	lst1 = list(map(int, input().split()))
	for i in range(n - 2):
		if (lst1[i] - lst1[i + 1]) * (lst1[i + 2] - lst1[i + 1]) < 0:
			lst[lst1[i + 1]] = -1
			count += 1
	print(n - count)
	for j in range(n):
		if lst[lst1[j]] != -1:
			print(lst1[j], end=' ')
	print()


import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	n = int(input())
	A = list(map(int, input().split()))
	B = [A[0]]
	for i in range(2, n):
		flag = 1
		if A[i - 1] < A[i - 2] and A[i] > A[i - 1]:
			B.append(A[i - 1])
			v1 = A[i]
			flag = 0
		elif A[i - 1] > A[i - 2] and A[i] < A[i - 1]:
			B.append(A[i - 1])
			v1 = A[i]
			flag = 0
	B.append(A[n - 1])
	print(len(B))
	print(*B)


import sys, math
input = lambda : sys.stdin.readline().rstrip()

def mech(a, b, c):
	(a, b) = (max(a, b), min(a, b))
	if c <= a and c >= b:
		return True
	return False
for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [p[0]]
	for i in range(1, n - 1):
		if mech(p[i - 1], p[i + 1], p[i]):
			continue
		else:
			ans.append(p[i])
	ans.append(p[-1])
	print(len(ans))
	print(*ans)


t = int(input())
while t:
	n = int(input())
	l1 = [int(x) for x in input().split()]
	i = 1
	l2 = []
	for x in range(len(l1)):
		if x == 0 or x == len(l1) - 1 or (l1[x] < l1[x + 1]) == (l1[x] < l1[x - 1]):
			l2.append(l1[x])
	print(len(l2))
	print(*l2)
	t -= 1


q = int(input())
for z in range(q):
	n = int(input())
	arr = list(map(int, input().split(' ')))
	up = True if arr[0] < arr[1] else False
	for i in range(1, n - 1):
		if up:
			if arr[i] < arr[i + 1]:
				arr[i] = 0
			else:
				up = False
		elif arr[i] > arr[i + 1]:
			arr[i] = 0
		else:
			up = True
	am = 0
	for x in arr:
		if x != 0:
			am += 1
	print(am)
	for x in arr:
		if x != 0:
			print(x, end=' ')
	print()


import sys
input = sys.stdin.readline

def solve():
	n = int(input())
	lista = list(map(int, input().split()))
	aux = []
	for k in range(n):
		if k == 0 or k == n - 1 or (lista[k - 1] < lista[k]) != (lista[k] < lista[k + 1]):
			aux.append(lista[k])
	print(len(aux))
	for i in aux:
		print(i, end=' ')
	print()
test = int(input())
while test != 0:
	solve()
	test -= 1


import sys
max_int = 1000000001
min_int = -max_int
t = int(input())
for _t in range(t):
	n = int(sys.stdin.readline())
	p = list(map(int, sys.stdin.readline().split()))
	d = prev_d = 0
	out = [p[0]]
	for i in range(1, n):
		if p[i] == p[i - 1]:
			continue
		if p[i] > p[i - 1]:
			d = 1
		else:
			d = -1
		if not prev_d:
			prev_d = d
		if d and d != prev_d:
			out.append(p[i - 1])
			prev_d = d
	out.append(p[-1])
	print(len(out))
	print(' '.join(map(str, out)))


def solve(n, a):
	stack = []
	for x in a:
		if len(stack) >= 2:
			if stack[-2] < stack[-1] < x:
				stack.pop()
			elif stack[-2] > stack[-1] > x:
				stack.pop()
		stack.append(x)
	return stack
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	s = solve(n, a)
	print(len(s))
	print(' '.join(map(str, s)))


def main():
	n = int(input())
	p = list(map(int, input().split()))
	ans = [p[0]]
	for i in range(1, n - 1):
		if p[i] > p[i - 1] and p[i] > p[i + 1]:
			ans.append(p[i])
		elif p[i] < p[i - 1] and p[i] < p[i + 1]:
			ans.append(p[i])
	ans.append(p[-1])
	print(len(ans))
	print(*ans)
for _ in range(int(input())):
	main()


t = int(input())
while t > 0:
	t -= 1
	n = int(input())
	a = [int(x) for x in input().split()]
	ans = []
	for i in range(n):
		if i == 0 or i == n - 1:
			ans.append(a[i])
		elif a[i - 1] < a[i] and a[i] > a[i + 1] or (a[i - 1] > a[i] and a[i] < a[i + 1]):
			ans.append(a[i])
	print(len(ans))
	print(*ans)


import sys
input = sys.stdin.readline
for f in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	up = True
	if p[1] < p[0]:
		up = False
	for i in range(2, n):
		sup = True
		if p[i] < p[i - 1]:
			sup = False
		if sup == up:
			p[i - 1] = 0
		else:
			up = sup
	sol = [p[0]]
	s = 1
	for i in range(1, n):
		if p[i] > 0:
			sol.append(p[i])
			s += 1
	print(s)
	print(*sol)


t = int(input())
for testcase in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	output = []
	output.append(a[0])
	toggle = 0
	if a[1] < a[0]:
		toggle = 1
	for i in range(1, n):
		if toggle == 0 and a[i] < a[i - 1]:
			output.append(a[i - 1])
			toggle = 1
		elif toggle == 1 and a[i] >= a[i - 1]:
			output.append(a[i - 1])
			toggle = 0
	output.append(a[n - 1])
	print(len(output))
	print(*output)


from collections import defaultdict, Counter
import copy, math
from copy import deepcopy
s = 'abcdefghijklmnopqrstuvwxyz' * 7
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ll = []
	i = 0
	while i < n - 1:
		if l[i] >= l[i + 1]:
			if len(ll) > 0 and l[i] != ll[-1]:
				ll.append(l[i])
			elif len(ll) == 0:
				ll.append(l[i])
			j = i
			while i < n - 1 and l[i] >= l[i + 1]:
				i += 1
			if j < i:
				ll.append(l[i])
		elif i < n - 1 and l[i] <= l[i + 1]:
			if len(ll) > 0 and l[i] != ll[-1]:
				ll.append(l[i])
			elif len(ll) == 0:
				ll.append(l[i])
			j = i
			while i < n - 1 and l[i] <= l[i + 1]:
				i += 1
			if j < i:
				ll.append(l[i])
		else:
			i += 1
	print(len(ll))
	print(*ll)


def compar(a, b):
	if a > b:
		return '+'
	else:
		return '-'
for _ in range(int(input())):
	p = int(input())
	lst = list(map(int, input().split()))
	lst1 = list()
	lst_assign = [0]
	lst_ans = list()
	for i in range(1, len(lst)):
		if compar(lst[i], lst[i - 1]) == '+':
			if lst_assign.pop() == '-':
				lst_ans.append(lst1.pop())
				lst1.clear()
			lst1.append(lst[i])
			lst_assign.append('+')
		else:
			if lst_assign.pop() == '+':
				lst_ans.append(lst1.pop())
				lst1.clear()
			lst_assign.append('-')
			lst1.append(lst[i])
	lst_ans.append(lst[p - 1])
	lst_ans.insert(0, lst[0])
	str1 = ' '.join(map(str, lst_ans))
	print(len(lst_ans))
	print(str1)


t = int(input())
for _ in range(t):
	n = int(input())
	x = list(map(int, input().split()))
	dp = [0] * n
	if x[1] > x[0]:
		dp[0] = 1
	for i in range(n - 1):
		if x[i + 1] > x[i]:
			dp[i + 1] = 1
	q = [x[0]]
	for i in range(1, n - 1):
		if dp[i] == 1:
			if dp[i + 1] == 0:
				q.append(x[i])
		elif dp[i + 1] == 1:
			q.append(x[i])
	q.append(x[-1])
	print(len(q))
	print(*q)


for _ in ' ' * int(input()):
	a = int(input())
	b = list(map(int, input().split()))
	c = b[:2]
	for i in range(2, a):
		if abs(c[-1] - c[-2]) + abs(c[-1] - b[i]) <= abs(c[-2] - b[i]):
			c.pop()
		c += [b[i]]
	print(len(c))
	print(*c)


t = int(input())
for test in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	if n == 2:
		print(2)
		print(*a)
	else:
		ans = [a[0]]
		i = 1
		while i < n:
			if a[i] > a[i - 1]:
				while i < n and a[i] > a[i - 1]:
					i += 1
				ans.append(a[i - 1])
			else:
				while i < n and a[i] < a[i - 1]:
					i += 1
				ans.append(a[i - 1])
		print(len(ans))
		print(*ans)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if n == 2:
		print(n)
		print(' '.join(map(str, a)))
		continue
	c = [a[0]]
	z = a[0]
	for i in range(1, n - 1):
		if a[i] > a[i - 1] and a[i] > a[i + 1]:
			c.append(a[i])
		elif a[i] < a[i - 1] and a[i] < a[i + 1]:
			c.append(a[i])
	c.append(a[n - 1])
	print(len(c))
	print(' '.join(map(str, c)))


from sys import stdin
import math

def inp():
	return stdin.readline().strip()
t = int(inp())
for _ in range(t):
	n = int(inp())
	ar = [int(x) for x in inp().split()]
	ans = [ar[0]]
	for i in range(n - 1):
		if i > 0:
			if ar[i - 1] < ar[i] > ar[i + 1] or ar[i - 1] > ar[i] < ar[i + 1]:
				ans.append(ar[i])
	ans.append(ar[n - 1])
	print(len(ans))
	print(*ans)


import sys
input = sys.stdin.buffer.readline

def I():
	return list(map(int, input().split()))

def sieve(n):
	a = [1] * n
	for i in range(2, n):
		if a[i]:
			for j in range(i * i, n, i):
				a[j] = 0
	return a
for __ in range(int(input())):
	n = int(input())
	arr = I()
	c = 0
	ans = []
	i = 0
	while i < n:
		if i == n - 1:
			ans.append(arr[i])
			break
		ans.append(arr[i])
		if arr[i] > arr[i + 1]:
			while i < n - 1 and arr[i] >= arr[i + 1]:
				i += 1
		else:
			while i < n - 1 and arr[i] <= arr[i + 1]:
				i += 1
	print(len(ans))
	print(*ans)


from math import gcd, sqrt
for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = [arr[0]]
	inc = 1
	if arr[1] < arr[0]:
		inc = 0
	for i in range(2, n):
		if inc:
			if arr[i] < arr[i - 1]:
				ans.append(arr[i - 1])
				inc = 0
		elif arr[i] > arr[i - 1]:
			ans.append(arr[i - 1])
			inc = 1
	ans.append(arr[-1])
	print(len(ans))
	print(*ans)


import math

def printans(arr):
	print(' '.join([str(x) for x in arr]))
t = int(input())
for i in range(t):
	n = int(input())
	arr = [int(x) for x in input().split(' ')]
	if len(arr) == 2:
		print(2)
		printans(arr)
		continue
	dir = 0
	curr = arr[0]
	ans = [arr[0]]
	for a in arr[1:]:
		if a == curr:
			continue
		elif a > curr:
			if dir == 0:
				dir = 1
				ans.append(a)
				curr = a
			elif dir == 1:
				ans.pop(-1)
				ans.append(a)
				curr = a
			elif dir == -1:
				ans.append(a)
				curr = a
				dir = 1
		elif a < curr:
			if dir == 0:
				dir = -1
				ans.append(a)
				curr = a
			elif dir == 1:
				ans.append(a)
				curr = a
				dir = -1
			elif dir == -1:
				ans.pop(-1)
				ans.append(a)
				curr = a
	print(len(ans))
	printans(ans)


for _ in range(int(input())):
	i = int(input())
	l = list(map(int, input().split()))
	p = l[0]
	n = []
	t = 'dd'
	c = 'dd'
	for x in l[1:]:
		if p < x:
			t = False
		else:
			t = True
		if c != t:
			c = t
			n.append(p)
		p = x
	n.append(p)
	print(len(n))
	print(*n)


from sys import stdin
input = stdin.readline
for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = [a[0]]
	pm = 0
	if a[1] > a[0]:
		pm = 1
	else:
		pm = -1
	for x in range(2, n):
		t = 1 if a[x] > a[x - 1] else -1
		if pm == t:
			continue
		b.append(a[x - 1])
		pm = t
	b.append(a[-1])
	print(len(b))
	for x in b:
		print(x, end=' ')
	print()


import sys
import math
import collections
import heapq
import queue
import itertools
import functools
import operator
import time
readline = sys.stdin.readline
IPS = lambda : readline().rstrip()
IP = lambda : int(readline().rstrip())
MP = lambda : map(int, readline().split())
LS = lambda : list(map(int, readline().split()))

def solve():
	n = IP()
	arr = LS()
	if n == 2:
		print(2)
		print(arr[0], arr[1])
	else:
		ans = []
		(i, j, tp) = (0, 1, 0)
		ans.append(arr[i])
		while i < n and j < n:
			if arr[j] > arr[i]:
				tp = j + 1
				while tp < n and arr[tp] > arr[j]:
					tp += 1
					j += 1
			elif arr[j] < arr[i]:
				tp = j + 1
				while tp < n and arr[tp] < arr[j]:
					tp += 1
					j += 1
			ans.append(arr[j])
			i = j
			j = i + 1
		print(len(ans))
		for elem in ans:
			print(elem, end=' ')
		print()
for _ in range(IP()):
	solve()


T = int(input())
for t in range(T):
	n = int(input())
	a = [int(i) for i in input().split()]
	sum = 0
	for i in range(1, n):
		sum += abs(a[i] - a[i - 1])
	b = [False for i in range(n)]
	k = 0
	for i in range(1, n - 1):
		x = abs(a[i - 1] - a[i])
		y = abs(a[i] - a[i + 1])
		z = abs(a[i + 1] - a[i - 1])
		if x + y == z:
			b[i] = True
			k += 1
	print(n - k)
	for i in range(n):
		if not b[i]:
			print(a[i], end=' ')


t = input()
for _ in range(int(t)):
	n = int(input())
	arr = list(map(int, input().split()))
	last = 0
	current = 0
	result = []
	index = 0
	result.append(arr[0])
	while index < n:
		if index < n - 1 and arr[index] < arr[index + 1]:
			while index < n - 1 and arr[index] < arr[index + 1]:
				index += 1
			result.append(arr[index])
		if index < n - 1 and arr[index] > arr[index + 1]:
			while index < n - 1 and arr[index] > arr[index + 1]:
				index += 1
			result.append(arr[index])
		if index == n - 1:
			break
	print(len(result))
	for item in result:
		print(item, end=' ')
	print()


import math
t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	a = False
	ans = [l[0]]
	for i in range(2, n):
		if l[i - 1] < l[i] and l[i - 2] > l[i - 1] or (l[i - 1] > l[i] and l[i - 2] < l[i - 1]):
			ans.append(l[i - 1])
	ans.append(l[-1])
	print(len(ans))
	print(*ans)


def corona(n, a):
	if a[1] - a[0] > 0:
		slope = '+'
	else:
		slope = '-'
	x = [0]
	last = None
	for i in range(1, n):
		if a[i] > a[i - 1]:
			if slope == '+':
				last = i
			else:
				x.append(last)
				slope = '+'
				last = i
		elif slope == '-':
			last = i
		else:
			x.append(last)
			slope = '-'
			last = i
		if i == n - 1:
			x.append(last)
	print(len(x))
	for j in x:
		print(a[j], end=' ')
	print()
	return
t = int(input())
a = []
for i in range(t):
	b = int(input())
	c = list(map(int, input().split(' ')))
	a.append([b, c])
for x in a:
	corona(*x)


t = int(input())
for i in range(0, t):
	n = int(input())
	L = list(map(int, input().split()))
	M = [L[0]]
	for i in range(1, len(L) - 1):
		if (L[i - 1] < L[i]) == (L[i] > L[i + 1]):
			M.append(L[i])
	M.append(L[-1])
	print(len(M))
	print(*M)


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	seq = [p[0], p[1]]
	for i in range(2, n):
		if abs(p[i] - seq[-2]) > abs(seq[-2] - seq[-1]):
			if abs(seq[-2] - p[i]) >= abs(seq[-1] - p[i]) + abs(seq[-1] - seq[-2]):
				seq.pop(-1)
			seq.append(p[i])
		else:
			if abs(p[i] - seq[-2]) == abs(seq[-2] - seq[-1]) + abs(p[i] - seq[-1]):
				seq.pop(-1)
			seq.append(p[i])
	if seq[-1] != p[-1]:
		seq.append(p[-1])
	print(len(seq))
	print(*seq)


from sys import stdin, stdout
import math
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	l = list(map(int, stdin.readline().split()))
	ans = [l[0]]
	for i in range(1, n - 1):
		if l[i - 1] < l[i] < l[i + 1]:
			continue
		if l[i - 1] > l[i] > l[i + 1]:
			continue
		ans.append(l[i])
	ans += [l[-1]]
	print(len(ans))
	stdout.write(' '.join(map(str, ans)) + '\n')


T = int(input())
for t in range(T):
	n = int(input())
	A = list(map(int, input().split()))
	pos = A[0]
	curr = A[1]
	sm = 0
	ans = [A[0]]
	for i in range(2, n):
		if (A[i - 1] > A[i - 2]) == (A[i] > A[i - 1]):
			curr = A[i]
		else:
			pos = curr
			curr = A[i]
			ans.append(pos)
	ans.append(curr)
	print(len(ans))
	for a in ans:
		print(a, end=' ')
	print('')


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	ans = [a[0]]
	if a[0] > a[1]:
		temp = 'small'
	else:
		temp = 'big'
	for i in range(1, n - 1):
		if temp == 'big':
			if a[i] < a[i + 1]:
				continue
			else:
				ans.append(a[i])
		elif a[i] > a[i + 1]:
			continue
		else:
			ans.append(a[i])
		if a[i] > a[i + 1]:
			temp = 'small'
		else:
			temp = 'big'
	ans.append(a[-1])
	print(len(ans))
	print(*ans)


import sys
import math

def II():
	return int(sys.stdin.readline())

def LI():
	return list(map(int, sys.stdin.readline().split()))

def MI():
	return map(int, sys.stdin.readline().split())

def SI():
	return sys.stdin.readline().strip()
t = II()
for q in range(t):
	n = II()
	p = LI()
	gr = False
	tr = False
	ans = [p[0], p[1]]
	if p[0] < p[1]:
		gr = True
	else:
		tr = True
	for i in range(2, n):
		if gr and p[i] > p[i - 1]:
			ans.pop(-1)
			ans.append(p[i])
		elif tr and p[i] < p[i - 1]:
			ans.pop(-1)
			ans.append(p[i])
		else:
			gr = False if gr else True
			tr = False if tr else True
			ans.append(p[i])
	print(len(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(c) for c in input().split()]
	sol = [0 for i in range(n)]
	for i in range(1, n - 1):
		if (arr[i] > arr[i + 1]) == (arr[i] > arr[i - 1]):
			sol[i] = 1
	sol[0] = 1
	sol[n - 1] = 1
	ans = [arr[i] for i in range(n) if sol[i]]
	print(len(ans))
	print(' '.join([str(c) for c in ans]))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	dels = [False] * n
	i = 1
	prev = i - 1
	while i < n:
		if i < n - 1 and abs(a[prev] - a[i + 1]) >= abs(a[i] - a[i + 1]) and (abs(a[prev] - a[i]) < abs(a[prev] - a[i + 1])):
			dels[i] = True
			prev = i - 1
		else:
			prev = i
		i += 1
	ans = []
	for i in range(n):
		if dels[i] == False and i < n - 1 and (a[i] != a[i + 1] or (a[i] == a[i + 1] and dels[i + 1] == True)):
			ans.append(a[i])
		elif i >= n - 1 and dels[i] == False:
			ans.append(a[i])
	print(len(ans))
	print(*ans)


tc = int(input())
while tc > 0:
	n = int(input())
	arr = list(map(int, input().split()))
	i = 0
	arr2 = []
	j = 0
	while i < n - 1:
		j = i + 1
		arr2.append(arr[i])
		if arr[i + 1] > arr[i]:
			while j < n and arr[j] > arr[j - 1]:
				j += 1
		else:
			while j < n and arr[j] < arr[j - 1]:
				j += 1
		i = j - 1
	arr2.append(arr[j - 1])
	print(len(arr2))
	print(*arr2)
	tc -= 1


def read_int():
	n = int(input())
	return n

def read_ints():
	ints = [int(x) for x in input().split(' ')]
	return ints

def solve(n, p):
	res = n
	inc = True if p[1] > p[0] else False
	idx = [0 for _ in range(n)]
	idx[0] = 1
	idx[-1] = 1
	for i in range(1, n - 1):
		if inc:
			if p[i + 1] > p[i]:
				res -= 1
			else:
				inc = False
				idx[i] = 1
		elif p[i + 1] < p[i]:
			res -= 1
		else:
			inc = True
			idx[i] = 1
	arr = []
	for i in range(n):
		if idx[i] == 1:
			arr.append(str(p[i]))
	return (res, arr)
t = read_int()
for case in range(t):
	n = read_int()
	p = read_ints()
	(res, arr) = solve(n, p)
	print(res)
	print(' '.join(arr))


t = int(input())
for _ in range(t):
	k = int(input())
	s = list(map(int, input().split()))
	if k <= 2:
		print(k)
		print(*s)
	else:
		ans = [s[0]]
		prev = s[0]
		for i in range(1, k - 1):
			if abs(prev - s[i]) + abs(s[i] - s[i + 1]) > abs(s[i + 1] - prev):
				prev = s[i]
				ans.append(s[i])
		ans.append(s[-1])
		print(len(ans))
		print(*ans)


import sys
input = sys.stdin.readline
ipnl = lambda n: [int(input()) for _ in range(n)]
inp = lambda : int(input())
ip = lambda : [int(w) for w in input().split()]
for _ in range(inp()):
	n = inp()
	x = ip()
	y = [x[0]]
	prev = -1
	for i in range(1, n):
		if x[i] > x[i - 1]:
			now = 'more'
		else:
			now = 'less'
		if prev == 'less':
			if now == 'less':
				y.pop()
		elif prev == 'more':
			if now == 'more':
				y.pop()
		y.append(x[i])
		prev = now
	print(len(y))
	print(*y)


from sys import stdin, stdout
nmbr = lambda : int(stdin.readline())
lst = lambda : list(map(int, stdin.readline().split()))
for _ in range(nmbr()):
	n = nmbr()
	a = lst()
	ans = [a[0]]
	p = 0
	while p < n:
		p1 = p2 = p
		while p1 + 1 < n and a[p1 + 1] > a[p1]:
			p1 += 1
		while p2 + 1 < n and a[p2 + 1] < a[p2]:
			p2 += 1
		if p1 != p:
			ans += [a[p1]]
			p = p1
		elif p2 != p:
			ans += [a[p2]]
			p = p2
		else:
			p += 1
	print(len(ans))
	print(*ans)


from sys import stdin, setrecursionlimit, stdout
from collections import deque
from math import sqrt, floor, ceil, log, log2, log10, pi, gcd, sin, cos, asin

def ii():
	return int(stdin.readline())

def fi():
	return float(stdin.readline())

def mi():
	return map(int, stdin.readline().split())

def fmi():
	return map(float, stdin.readline().split())

def li():
	return list(mi())

def si():
	return stdin.readline().rstrip()

def lsi():
	return list(si())
res = ['Yes', 'No']
test_case = ii()
while test_case:
	test_case -= 1
	n = ii()
	a = li()
	f = 1
	if a[1] > a[0]:
		f = 0
	ans = [a[0]]
	for i in range(2, n):
		if f and a[i] > a[i - 1]:
			ans.append(a[i - 1])
			f = 0
		elif not f and a[i] < a[i - 1]:
			ans.append(a[i - 1])
			f = 1
	ans.append(a[-1])
	print(len(ans))
	print(*ans)


t = int(input())
while t:
	n = int(input())
	l1 = list(map(int, input().split()))
	l2 = []
	l2.append(l1[0])
	count = 1
	for i in range(1, n - 1):
		if l1[i] > l1[i - 1] and l1[i] < l1[i + 1] or (l1[i] < l1[i - 1] and l1[i] > l1[i + 1]):
			pass
		else:
			l2.append(l1[i])
			count = count + 1
	l2.append(l1[-1])
	count = count + 1
	print(count)
	print(*l2)
	t = t - 1


t = int(input())
for test in range(t):
	n = int(input())
	nums = list(map(int, input().split()))
	ans = []
	for i in range(n):
		if i > 0 and i < n - 1:
			if nums[i] < nums[i + 1] and nums[i - 1] < nums[i] or (nums[i] > nums[i + 1] and nums[i - 1] > nums[i]):
				continue
			else:
				ans.append(nums[i])
		else:
			ans.append(nums[i])
	print(len(ans))
	print(*ans)


def check(l):
	if len(l) == 2:
		print(2)
		for i in range(2):
			if i == 1:
				print(l[i])
			else:
				print(l[i], end=' ')
	else:
		to_send = [l[0]]
		curr = l[0]
		for i in range(1, len(l) - 1):
			if curr < l[i] and l[i] <= l[i + 1]:
				if i + 1 == len(l) - 1:
					to_send.append(l[i + 1])
				curr = l[i]
				continue
			elif curr > l[i] and l[i] >= l[i + 1]:
				if i + 1 == len(l) - 1:
					to_send.append(l[i + 1])
				curr = l[i]
				continue
			elif curr > l[i] and l[i] < l[i + 1]:
				if i + 1 == len(l) - 1:
					to_send.append(l[i])
					to_send.append(l[i + 1])
				else:
					to_send.append(l[i])
			elif curr < l[i] and l[i] > l[i + 1]:
				if i + 1 == len(l) - 1:
					to_send.append(l[i])
					to_send.append(l[i + 1])
				else:
					to_send.append(l[i])
			curr = l[i]
		k = len(to_send)
		print(k)
		for i in range(len(to_send)):
			if i == k - 1:
				print(to_send[i])
			else:
				print(to_send[i], end=' ')
t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().strip().split()))
	check(l)


from math import *
from collections import *
from operator import itemgetter
import bisect
from heapq import *
i = lambda : input()
ii = lambda : int(input())
iia = lambda : list(map(int, input().split()))
isa = lambda : list(input().split())
I = lambda : list(map(int, input().split()))
chrIdx = lambda x: ord(x) - 96
idxChr = lambda x: chr(96 + x)

def find(a, i):
	x = bin(i)[2:]
	if x.count('1') < 2:
		return [0, []]
	else:
		prev = 0
		cur = 0
		new = []
		for i in range(len(x)):
			if x[i] == '1':
				new.append(a[i])
		for i in range(len(new) - 1):
			cur += abs(new[i] - new[i + 1])
		return [cur, new]
t = ii()
for _ in range(t):
	n = ii()
	a = iia()
	prev = 0
	maxi = 0
	ans = 0
	inc = 0
	ans = []
	i = 0
	while i < n - 1:
		if i < n - 1 and a[i] < a[i + 1]:
			if len(ans) > 0 and ans[-1] != a[i]:
				ans.append(a[i])
			elif len(ans) == 0:
				ans.append(a[i])
			j = i + 1
			while j < n - 1 and a[j] < a[j + 1]:
				j += 1
			ans.append(a[j])
			i = j
		elif i < n - 1 and a[i] > a[i + 1]:
			if len(ans) > 0 and ans[-1] != a[i]:
				ans.append(a[i])
			elif len(ans) == 0:
				ans.append(a[i])
			j = i + 1
			while j < n - 1 and a[j] > a[j + 1]:
				j += 1
			ans.append(a[j])
			i = j
	print(len(ans))
	print(*ans)


t = int(input())
while t != 0:
	n = int(input())
	list1 = list(map(int, input().split()))
	ans = list()
	i = 0
	ans.append(list1[0])
	j = 1
	while i < n and j < n:
		if i < n and j < n and (list1[j] > list1[i]):
			while i < n and j < n and (list1[j] > list1[i]):
				i += 1
				j += 1
			ans.append(list1[i])
		else:
			while i < n and j < n and (list1[j] < list1[i]):
				i += 1
				j += 1
			ans.append(list1[i])
	print(len(ans))
	print(*ans)
	t -= 1


t = int(input())
for i in range(t):
	n = int(input())
	b = list(map(int, input().split()))
	s = [b[0]]
	j = 1
	while j < n - 1:
		if b[j + 1] - b[j] > 0 and b[j] - b[j - 1] < 0:
			s.append(b[j])
		elif b[j + 1] - b[j] < 0 and b[j] - b[j - 1] > 0:
			s.append(b[j])
		j += 1
	s.append(b[-1])
	print(len(s))
	print(*s)


import sys
input = sys.stdin.readline
INF = 10 ** 18
for _ in range(int(input())):
	n = int(input())
	P = list(map(int, input().split()))
	S = [P[0], P[1]]
	for i in range(2, n):
		v = P[i]
		while len(S) >= 2:
			if S[-2] < S[-1] < v or S[-2] > S[-1] > v:
				S.pop()
			else:
				break
		S.append(v)
	print(len(S))
	print(' '.join(map(str, S)))


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	final = [l[0]]
	cont_sum = 0
	for i in range(1, n):
		cont_sum += abs(l[i] - l[i - 1])
		curr_sum = abs(l[i] - final[-1])
		if curr_sum < cont_sum:
			final.append(l[i - 1])
			cont_sum = abs(l[i] - l[i - 1])
	final.append(l[-1])
	print(len(final))
	print(*final)


def sol(l):
	if len(l) == 2:
		return l
	if len(l) > 2:
		dell = []
		for x in range(len(l) - 2):
			if l[x + 2] > l[x + 1] > l[x]:
				dell.append(x + 1)
			elif l[x + 2] < l[x + 1] < l[x]:
				dell.append(x + 1)
		for x in reversed(dell):
			del l[x]
		return l
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	v = sol(l)
	print(len(v))
	for x in range(len(v) - 1):
		print(v[x], end=' ')
	print(v[len(v) - 1])


t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	a = [p[0]]
	up = p[1] > p[0]
	i = 2
	while i < n:
		if (p[i] > p[i - 1]) == up:
			pass
		else:
			a.append(p[i - 1])
			up = p[i] > a[-1]
		i += 1
	a.append(p[-1])
	print(len(a))
	for i in a:
		print(i, end=' ')
	print()


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	total = [l[0]]
	count = n
	for j in range(1, n - 1):
		if abs(l[j] - l[j - 1]) + abs(l[j] - l[j + 1]) == abs(l[j - 1] - l[j + 1]):
			count -= 1
		else:
			total.append(l[j])
	total.append(l[-1])
	print(count)
	print(*total)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	res = []
	d = dict()
	for i in range(1, n - 1):
		if a[i] > a[i - 1] and a[i] < a[i + 1] or (a[i] < a[i - 1] and a[i] > a[i + 1]):
			pass
		else:
			res.append(a[i])
	print(len(res) + 2)
	print(a[0], *res, a[n - 1])


import sys, bisect, string, math, time, functools, random, fractions
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
from itertools import permutations, combinations, groupby
rep = range

def Golf():
	(n, *t) = map(int, open(0).read().split())

def I():
	return int(input())

def S_():
	return input()

def IS():
	return input().split()

def LS():
	return [i for i in input().split()]

def MI():
	return map(int, input().split())

def LI():
	return [int(i) for i in input().split()]

def LI_():
	return [int(i) - 1 for i in input().split()]

def NI(n):
	return [int(input()) for i in range(n)]

def NI_(n):
	return [int(input()) - 1 for i in range(n)]

def StoLI():
	return [ord(i) - 97 for i in input()]

def ItoS(n):
	return chr(n + 97)

def LtoS(ls):
	return ''.join([chr(i + 97) for i in ls])

def RA():
	return map(int, open(0).read().split())

def GI(V, E, ls=None, Directed=False, index=1):
	org_inp = []
	g = [[] for i in range(V)]
	FromStdin = True if ls == None else False
	for i in range(E):
		if FromStdin:
			inp = LI()
			org_inp.append(inp)
		else:
			inp = ls[i]
		if len(inp) == 2:
			(a, b) = inp
			c = 1
		else:
			(a, b, c) = inp
		if index == 1:
			a -= 1
			b -= 1
		aa = (a, c)
		bb = (b, c)
		g[a].append(bb)
		if not Directed:
			g[b].append(aa)
	return (g, org_inp)

def GGI(h, w, search=None, replacement_of_found='.', mp_def={'#': 1, '.': 0}, boundary=1):
	mp = [boundary] * (w + 2)
	found = {}
	for i in range(h):
		s = input()
		for char in search:
			if char in s:
				found[char] = (i + 1) * (w + 2) + s.index(char) + 1
				mp_def[char] = mp_def[replacement_of_found]
		mp += [boundary] + [mp_def[j] for j in s] + [boundary]
	mp += [boundary] * (w + 2)
	return (h + 2, w + 2, mp, found)

def TI(n):
	return GI(n, n - 1)

def accum(ls):
	rt = [0]
	for i in ls:
		rt += [rt[-1] + i]
	return rt

def bit_combination(n, base=2):
	rt = []
	for tb in range(base ** n):
		s = [tb // base ** bt % base for bt in range(n)]
		rt += [s]
	return rt

def gcd(x, y):
	if y == 0:
		return x
	if x % y == 0:
		return y
	while x % y != 0:
		(x, y) = (y, x % y)
	return y

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)
YN = ['YES', 'NO']
Yn = ['Yes', 'No']
mo = 10 ** 9 + 7
inf = float('inf')
FourNb = [(-1, 0), (1, 0), (0, 1), (0, -1)]
EightNb = [(-1, 0), (1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]
compas = dict(zip('WENS', FourNb))
cursol = dict(zip('LRUD', FourNb))
l_alp = string.ascii_lowercase
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
input = lambda : sys.stdin.readline().rstrip()

class Tree:

	def __init__(self, inp_size=None, ls=None, init=True, index=1):
		self.LCA_init_stat = False
		self.ETtable = []
		if init:
			if ls == None:
				self.stdin(inp_size, index=index)
			else:
				self.size = len(ls) + 1
				(self.edges, _) = GI(self.size, self.size - 1, ls, index=index)
		return

	def stdin(self, inp_size=None, index=1):
		if inp_size == None:
			self.size = int(input())
		else:
			self.size = inp_size
		(self.edges, _) = GI(self.size, self.size - 1, index=index)
		return

	def listin(self, ls, index=0):
		self.size = len(ls) + 1
		(self.edges, _) = GI(self.size, self.size - 1, ls, index=index)
		return

	def dfs(self, x, func=lambda pr, prv, nx, dist: prv + dist, root_v=0):
		q = deque([x])
		v = [None] * self.size
		v[x] = root_v
		while q:
			c = q.pop()
			for (nb, d) in self.edges[c]:
				if v[nb] == None:
					q.append(nb)
					v[nb] = func(c, v[c], nb, d)
		return v

	def bfs(self, x, func=lambda pr, prv, nx, dist: prv + dist, root_v=0):
		q = deque([x])
		v = [None] * self.size
		v[x] = root_v
		while q:
			c = q.popleft()
			for (nb, d) in self.edges[c]:
				if v[nb] == None:
					q.append(nb)
					v[nb] = func(c, v[c], nb, d)
		return v

	def parent(self, x):
		return self.dfs(0, func=lambda pr, prv, nx, dist: pr, root_v=-1)

	def topological_sort(self, x):
		tps = []
		q = deque([x])
		v = [None] * self.size
		v[x] = 0
		while q:
			c = q.popleft()
			tps.append(c)
			for (nb, d) in self.edges[c]:
				if v[nb] == None:
					q.append(nb)
					v[nb] = 0
		return tps

	def EulerTour(self, x):
		q = deque()
		q.append(x)
		self.depth = [None] * self.size
		self.depth[x] = 0
		self.ETtable = []
		self.ETdepth = []
		self.ETin = [-1] * self.size
		self.ETout = [-1] * self.size
		cnt = 0
		while q:
			c = q.pop()
			if c < 0:
				ce = ~c
			else:
				ce = c
				for (nb, d) in self.edges[ce]:
					if self.depth[nb] == None:
						q.append(~ce)
						q.append(nb)
						self.depth[nb] = self.depth[ce] + 1
			self.ETtable.append(ce)
			self.ETdepth.append(self.depth[ce])
			if self.ETin[ce] == -1:
				self.ETin[ce] = cnt
			else:
				self.ETout[ce] = cnt
			cnt += 1
		return

	def LCA_init(self, root):
		self.EulerTour(root)
		self.st = SparseTable(self.ETdepth, init_func=min, init_idl=inf)
		self.LCA_init_stat = True
		return

	def LCA(self, root, x, y):
		if self.LCA_init_stat == False:
			self.LCA_init(root)
		(xin, xout) = (self.ETin[x], self.ETout[x])
		(yin, yout) = (self.ETin[y], self.ETout[y])
		a = min(xin, yin)
		b = max(xout, yout, xin, yin)
		id_of_min_dep_in_et = self.st.query_id(a, b + 1)
		return self.ETtable[id_of_min_dep_in_et]

	def __str__(self):
		return str(self.edges)

	def show(self):
		if all([all([d == 1 for (nd, d) in edge]) for edge in self.edges]):
			print([[nd for (nd, d) in edge] for edge in self.edges])
		else:
			print(self)

class SparseTable:

	def __init__(self, ls, init_func=min, init_idl=float('inf')):
		self.func = init_func
		self.idl = init_idl
		self.size = len(ls)
		self.N0 = self.size.bit_length()
		self.table = [ls[:]]
		self.index = [list(range(self.size))]
		self.lg = [0] * (self.size + 1)
		for i in range(2, self.size + 1):
			self.lg[i] = self.lg[i >> 1] + 1
		for i in range(self.N0):
			tmp = [self.func(self.table[i][j], self.table[i][min(j + (1 << i), self.size - 1)]) for j in range(self.size)]
			tmp_id = [self.index[i][j] if self.table[i][j] == self.func(self.table[i][j], self.table[i][min(j + (1 << i), self.size - 1)]) else self.index[i][min(j + (1 << i), self.size - 1)] for j in range(self.size)]
			self.table += [tmp]
			self.index += [tmp_id]

	def query(self, l, r):
		if r > self.size:
			r = self.size
		N = self.lg[r - l]
		return self.func(self.table[N][l], self.table[N][max(0, r - (1 << N))])

	def query_id(self, l, r):
		if r > self.size:
			r = self.size
		N = self.lg[r - l]
		(a, b) = (self.index[N][l], self.index[N][max(0, r - (1 << N))])
		if self.table[0][a] == self.func(self.table[N][l], self.table[N][max(0, r - (1 << N))]):
			b = a
		return b

	def right_bound(self, pos, x):
		k = (self.size - pos).bit_length()
		for j in range(k)[::-1]:
			nx = pos + (1 << j)
			if nx < n and self.query(pos, nx + 1) <= x:
				pos += 1 << j
		return pos

	def left_bound(self, pos, x):
		k = pos.bit_length()
		for j in range(k)[::-1]:
			nx = pos - (1 << j)
			if 0 <= nx and self.query(nx, pos + 1) <= x:
				pos -= 1 << j
		return pos

	def __str__(self):
		return str(self.table[0])

	def print(self):
		for i in self.table:
			print(*i)
show_flg = False
show_flg = True
ans = 0
for _ in rep(I()):
	ans = 0
	n = I()
	a = LI()
	b = [a[0]]
	for i in range(1, n - 1):
		if (a[i] - a[i - 1]) * (a[i + 1] - a[i]) < 0:
			b += (a[i],)
	ans = b + [a[-1]]
	print(len(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	if n == 2:
		print(n)
		print(*a)
	else:
		l = [a[0]]
		dec = True
		st = 0
		for i in range(n):
			if a[i] < a[0]:
				dec = True
				st = i
				break
			elif a[i] > a[0]:
				dec = False
				st = i
				break
		i = st
		while i < n:
			if dec:
				j = i + 1
				while j < n and a[j] <= a[j - 1]:
					j += 1
				l.append(a[j - 1])
				i = j
				dec = False
			else:
				j = i + 1
				while j < n and a[j] >= a[j - 1]:
					j += 1
				l.append(a[j - 1])
				i = j
				dec = True
		print(len(l))
		print(*l)


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(x) for x in input().split(' ')]
	if n == 2:
		print(2)
		print(a[0], a[1])
		continue
	count = 0
	if a[0] != a[1]:
		s = f'{a[0]} '
		count += 1
	else:
		s = ''
	for i in range(1, n - 1):
		if a[i] >= a[i + 1] and a[i] >= a[i - 1] and (a[i - 1] != a[i + 1]) or (a[i] <= a[i + 1] and a[i] <= a[i - 1] and (a[i - 1] != a[i + 1])):
			s += f'{a[i]} '
			count += 1
	if a[n - 1] != a[n - 2]:
		s += f'{a[n - 1]}'
		count += 1
	elif len(s) == 0:
		s = f'{a[0]} {a[0]}'
		count = 2
	print(count)
	print(s)


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return list(map(int, input().split()))

def sociallyDistant(A):
	n = len(A)
	breaks = [0]
	for i in range(1, n - 1):
		if A[i] > A[i - 1] and A[i] > A[i + 1] or (A[i] < A[i - 1] and A[i] < A[i + 1]):
			breaks.append(i)
	breaks.append(n - 1)
	print(len(breaks))
	for i in breaks:
		print(A[i], end=' ')
t = inp()
while t:
	t -= 1
	n = inp()
	arr = invr()
	sociallyDistant(arr)


from __future__ import division, print_function
import sys
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
import os, sys, bisect, copy
from collections import defaultdict, Counter, deque
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
if os.path.exists('out.txt'):
	sys.stdout = open('out.txt', 'w')

def input():
	return sys.stdin.readline()

def mapi(arg=0):
	return map(int if arg == 0 else str, input().split())
for _ in range(int(input())):
	n = int(input())
	a = list(mapi())
	res = [a[0]]
	for i in range(1, n - 1):
		if a[i - 1] < a[i] and a[i + 1] < a[i]:
			res.append(a[i])
		if a[i - 1] > a[i] and a[i + 1] > a[i]:
			res.append(a[i])
	res.append(a[-1])
	print(len(res))
	print(*res)


def fix(l):
	include = [0]
	for i in range(1, len(l) - 1):
		if (l[i] - l[i - 1]) * (l[i + 1] - l[i]) < 0:
			include.append(i)
	include.append(len(l) - 1)
	return [l[x] for x in include]
t = int(input())
for i in range(t):
	input()
	l = [int(x) for x in input().strip().split(' ')]
	f = fix(l)
	print(len(f))
	print(' '.join([str(x) for x in f]))


t = int(input())
for i in range(t):
	n = int(input())
	a = [int(e) for e in input().split()]
	stack = [a[0], a[1]]
	for i in range(2, len(a)):
		if a[i - 2] <= a[i - 1] <= a[i] or a[i - 2] >= a[i - 1] >= a[i]:
			stack.pop()
		stack.append(a[i])
	print(len(stack))
	for e in stack:
		print(e, end=' ')
	print()


for test_i in range(int(input())):
	n = int(input())
	tran = list(map(int, input().split()))
	ans = [tran[0]]
	direct = tran[0] < tran[1]
	for i in range(1, n - 1):
		if (tran[i] < tran[i + 1]) != direct:
			ans.append(tran[i])
			direct = not direct
	ans.append(tran[-1])
	print(len(ans))
	print(*ans)


a = int(input())
for i in range(a):
	m = int(input())
	z = list(map(int, input().split()))
	ans = []
	for i in range(1, len(z)):
		if z[i] - z[i - 1] > 0:
			ans.append(1)
		else:
			ans.append(-1)
	fin = []
	fin.append(z[0])
	temp = []
	count = 1
	for i in range(1, len(ans)):
		if ans[i] == ans[i - 1]:
			count += 1
		else:
			temp.append(count)
			count = 1
	temp.append(count)
	ori = 0
	for i in range(len(temp)):
		fin.append(z[ori + temp[i]])
		ori += temp[i]
	print(len(fin))
	print(*fin)


import sys

def read():
	return int(input())

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_array():
	return list(map(int, sys.stdin.readline().strip().split()))

def input():
	return sys.stdin.readline().strip()

def solve():
	n = read()
	A = get_array()
	R = []
	for i in range(n):
		if i == 0 or i == n - 1:
			R.append(A[i])
		elif (A[i - 1] < A[i]) != (A[i] < A[i + 1]):
			R.append(A[i])
	print(len(R))
	for x in R:
		print('%d ' % x, end='')
	print()
cas = read()
while cas:
	cas -= 1
	solve()


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush
from math import *
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
sys.setrecursionlimit(int(pow(10, 6)))
mod = int(pow(10, 9) + 7)
mod2 = 998244353

def data():
	return sys.stdin.readline().strip()

def out(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sl():
	return list(ssp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(l()[0]):
	n = l()[0]
	A = [0] + l()
	V = [A[1], A[2]]
	for i in range(3, n + 1):
		if A[i] > V[-1] and V[-1] > V[-2]:
			V.pop()
			V.append(A[i])
		elif A[i] < V[-1] and V[-1] < V[-2]:
			V.pop()
			V.append(A[i])
		else:
			V.append(A[i])
	print(len(V))
	print(*V)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(j) for j in input().split()]
	sub = []
	sub.append(arr[0])
	count = 0
	for i in range(1, n - 1):
		if arr[i - 1] < arr[i] and arr[i] > arr[i + 1] or (arr[i - 1] > arr[i] and arr[i] < arr[i + 1]):
			sub.append(arr[i])
	sub.append(arr[-1])
	print(len(sub))
	print(*sub)


from sys import stdin, stdout
import math
from itertools import permutations, combinations
from collections import defaultdict
from bisect import bisect_left
from bisect import bisect_right

def L():
	return list(map(int, stdin.readline().split()))

def In():
	return map(int, stdin.readline().split())

def I():
	return int(stdin.readline())
P = 1000000007

def main():
	for t in range(I()):
		n = I()
		arr = L()
		if n == 2:
			print(2)
			print(*arr)
		else:
			lis = [arr[0]]
			j = 0
			flag = 0
			if arr[1] > arr[0]:
				flag = 1
			for i in range(2, n):
				if flag == 1 and arr[i] > arr[i - 1]:
					continue
				elif flag == 1 and arr[i] < arr[i - 1]:
					flag = 0
					lis.append(arr[i - 1])
				elif flag == 0 and arr[i] > arr[i - 1]:
					flag = 1
					lis.append(arr[i - 1])
				else:
					continue
			if lis[len(lis) - 1] != arr[n - 1]:
				lis.append(arr[n - 1])
			print(len(lis))
			print(*lis)
main()


kr = int(input())
for tkr in range(kr):
	n = int(input())
	k = n
	b = [int(i) for i in input().split()]
	a = [b[0]]
	for i in range(1, n - 1):
		if b[i - 1] < b[i] and b[i] < b[i + 1] or (b[i - 1] > b[i] and b[i] > b[i + 1]):
			k -= 1
			continue
		else:
			a += [b[i]]
	a += [b[n - 1]]
	print(k)
	print(*a)


from collections import *
from sys import stdin, stderr

def rl():
	return [int(w) for w in stdin.readline().split()]
(t,) = rl()
for _ in range(t):
	(n,) = rl()
	p = rl()
	s = [p[0]]
	for i in range(1, n - 1):
		if p[i - 1] < p[i] > p[i + 1] or p[i - 1] > p[i] < p[i + 1]:
			s.append(p[i])
	s.append(p[-1])
	print(len(s))
	print(*s)


for _ in range(int(input())):
	n = int(input())
	A = list(map(int, input().split()))
	Ans = [A[0]]
	p = 0
	q = 0
	for i in range(1, n):
		if A[i] > A[i - 1]:
			p = 1
			if q > 0:
				Ans.append(A[i - 1])
				q = 0
		else:
			q = 1
			if p > 0:
				Ans.append(A[i - 1])
				p = 0
	Ans.append(A[-1])
	print(len(Ans))
	print(*Ans)


t = int(input())
for i in range(t):
	l = []
	f = 0
	n = int(input())
	a = [int(i) for i in input().split()]
	temp = a[0]
	l.append(temp)
	if a[0] < a[1]:
		f = 0
	else:
		f = 1
	for j in range(n - 1):
		if temp < a[j + 1]:
			if f == 0:
				temp = a[j + 1]
			else:
				f = 0
				l.append(a[j])
				temp = a[j + 1]
		elif f == 1:
			temp = a[j + 1]
		else:
			f = 1
			l.append(a[j])
			temp = a[j + 1]
	l.append(temp)
	print(len(l), end='\n')
	for i in l:
		print(i, end=' ')
	print(end='\n')


t = int(input())
while t:
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	b.append(a[0])
	b.append(a[1])
	for i in range(2, n, 1):
		if b[-1] > b[-2] and a[i] > b[-1]:
			b.pop()
			b.append(a[i])
		elif b[-1] < b[-2] and a[i] < b[-1]:
			b.pop()
			b.append(a[i])
		else:
			b.append(a[i])
	print(len(b))
	for i in range(len(b)):
		print(b[i], end=' ')
	print()
	t = t - 1


t = int(input())
for jack in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	p = [a[0], a[1]]
	for i in range(2, n):
		if a[i] >= a[i - 1] >= a[i - 2] or a[i] <= a[i - 1] <= a[i - 2]:
			p[-1] = a[i]
		else:
			p.append(a[i])
	print(len(p))
	for i in p:
		print(i, end=' ')
	print()


n = int(input())
for i in range(n):
	t = int(input())
	c = list(map(int, input().split()))
	d = [c[0]]
	for j in range(1, t - 1):
		if c[j] > c[j + 1] and c[j] > c[j - 1]:
			d.append(c[j])
		elif c[j] < c[j + 1] and c[j] < c[j - 1]:
			d.append(c[j])
		else:
			pass
	d.append(c[t - 1])
	print(len(d))
	print(*d, sep=' ')


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().strip().split()))
	seq = [arr[0], arr[1]]
	inc = 1 if arr[1] >= arr[0] else -1
	for i in range(2, n):
		if inc == 1:
			if arr[i] >= arr[i - 1]:
				seq[-1] = arr[i]
			else:
				inc = -1
				seq.append(arr[i])
		elif arr[i] <= arr[i - 1]:
			seq[-1] = arr[i]
		else:
			inc = 1
			seq.append(arr[i])
	print(len(seq))
	print(*seq)


import sys
from sys import setrecursionlimit
setrecursionlimit(10 ** 5)
readline = sys.stdin.readline
for _ in range(int(readline())):
	n = int(readline())
	a = list(map(int, readline().split()))
	ans = [a[0]]
	for i in range(1, n - 1):
		if a[i - 1] > a[i] < a[i + 1] or a[i - 1] < a[i] > a[i + 1]:
			ans.append(a[i])
	ans.append(a[-1])
	print(len(ans))
	print(*ans)


t = int(input())
for i in range(t):
	n = int(input())
	p = input()
	p = p.split()
	for j in range(n):
		p[j] = int(p[j])
	z = [p[0]]
	x = 2
	for k in range(1, n - 1):
		if not (p[k - 1] < p[k] < p[k + 1] or p[k - 1] > p[k] > p[k + 1]):
			z.append(p[k])
			x += 1
	z.append(p[n - 1])
	print(x)
	for a in z:
		print(a, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = [a[0]]
	prev = ''
	for i in range(1, n):
		if a[i] - a[i - 1] > 0:
			if prev == 'decrease':
				b.append(a[i - 1])
			prev = 'increase'
		elif a[i] - a[i - 1] < 0:
			if prev == 'increase':
				b.append(a[i - 1])
			prev = 'decrease'
	b.append(a[n - 1])
	ans = 0
	print(len(b))
	print(*b)


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from math import sqrt, floor, factorial, gcd, log
from collections import deque, Counter, defaultdict
from itertools import permutations
from bisect import bisect
input = lambda : sys.stdin.readline().rstrip('\r\n')
read = lambda : list(map(int, input().strip().split(' ')))

def solve():
	for _ in range(int(input())):
		n = int(input())
		arr = read()
		ans = arr[:2]
		sign = [0, 1][arr[0] < arr[1]]
		for i in range(2, n):
			if abs(ans[-2] - arr[i]) < abs(ans[-2] - ans[-1]) + abs(ans[-1] - arr[i]):
				ans.append(arr[i])
			else:
				ans.pop()
				ans.append(arr[i])
		print(len(ans))
		print(*ans)
solve()


def fun(n, a):
	res = []
	res.append(a[0])
	for i in range(1, n - 1):
		if a[i - 1] < a[i]:
			if a[i] > a[i + 1]:
				res.append(a[i])
		elif a[i - 1] > a[i]:
			if a[i] < a[i + 1]:
				res.append(a[i])
	res.append(a[-1])
	return res
for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	res = fun(n, a)
	print(len(res))
	print(*res)


import sys
input = lambda : sys.stdin.readline().strip('\r\n')
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	s = [a[0]]
	for i in range(1, n - 1):
		if a[i - 1] < a[i] > a[i + 1] or (a[i] < a[i + 1] and a[i] < a[i - 1]):
			s.append(a[i])
	s.append(a[-1])
	print(len(s))
	print(*s)


import bisect
from itertools import accumulate
import os
import sys
import math
from decimal import *
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))

def input():
	return sys.stdin.readline().rstrip('\r\n')

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True

def SieveOfEratosthenes(n):
	prime = []
	primes = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if primes[p] == True:
			prime.append(p)
			for i in range(p * p, n + 1, p):
				primes[i] = False
		p += 1
	return prime

def primefactors(n):
	fac = []
	while n % 2 == 0:
		fac.append(2)
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 2):
		while n % i == 0:
			fac.append(i)
			n = n // i
	if n > 1:
		fac.append(n)
	return fac

def factors(n):
	fac = set()
	fac.add(1)
	fac.add(n)
	for i in range(2, int(math.sqrt(n)) + 1):
		if n % i == 0:
			fac.add(i)
			fac.add(n // i)
	return list(fac)

def NcR(n, r):
	p = 1
	k = 1
	if n - r < r:
		r = n - r
	if r != 0:
		while r:
			p *= n
			k *= r
			m = math.gcd(p, k)
			p //= m
			k //= m
			n -= 1
			r -= 1
	else:
		p = 1
	return p
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [a[0]]
	increasing = 0
	decreasing = 0
	for i in range(1, len(a) - 1):
		if a[i] > a[i - 1] and a[i] > a[i + 1]:
			ans.append(a[i])
		elif a[i] < a[i - 1] and a[i] < a[i + 1]:
			ans.append(a[i])
	ans.append(a[-1])
	print(len(ans))
	print(*ans)


def sign(a, b):
	return (a - b) // abs(a - b)
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	direction = sign(a[0], a[1])
	op = [a[0]]
	for i in range(1, n - 1):
		if direction != sign(a[i], a[i + 1]):
			op.append(a[i])
			direction *= -1
	op.append(a[n - 1])
	print(len(op))
	print(*op, sep=' ')


t = int(input())
for _ in range(t):
	n = int(input())
	array = [int(x) for x in input().split()]
	diff_array = [array[x] - array[x + 1] for x in range(n - 1)]
	prev = array[0]
	remove = {}
	for num in range(n - 2):
		remove.setdefault(num + 1, False)
		if diff_array[num] > 0 and diff_array[num + 1] > 0 or (diff_array[num] < 0 and diff_array[num + 1] < 0):
			remove[num + 1] = True
	print(n - len([x for x in remove.values() if x]))
	for i in range(n):
		remove.setdefault(i, False)
		if remove[i]:
			continue
		print(array[i], end=' ')
	print()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')

def main():
	for _ in range(N()):
		n = N()
		arr = RLL()
		res = [[arr[0], 3]]
		for i in range(1, n):
			now = []
			if arr[i] > arr[i - 1]:
				now = [arr[i], 1]
			else:
				now = [arr[i], 0]
			while now[1] == res[-1][1]:
				res.pop()
			res.append(now)
		print(len(res))
		print(*[i[0] for i in res])
main()


import sys
input = sys.stdin.buffer.readline

def isIncreasing(a, b):
	return a < b
t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(x) for x in input().split()]
	resStack = [arr[0]]
	i = 1
	d = isIncreasing(resStack[-1], arr[i])
	while True:
		if d != isIncreasing(arr[i - 1], arr[i]):
			resStack.append(arr[i - 1])
			d = isIncreasing(arr[i - 1], arr[i])
		i += 1
		if i == n:
			resStack.append(arr[i - 1])
			break
	print(len(resStack))
	print(' '.join([str(x) for x in resStack]))


for _ in range(int(input())):
	ans = []
	n = int(input())
	l = list(map(int, input().split()))
	if n == 1:
		print(l[0])
	elif n == 2:
		print(2)
		print(*l)
	else:
		inc = -1
		dec = -1
		if l[1] > l[0]:
			inc = 1
		else:
			dec = 1
		ans.append(l[0])
		for i in range(2, n):
			if l[i - 1] < l[i]:
				if inc == -1:
					ans.append(l[i - 1])
					inc = 1
					dec = -1
			elif dec == -1:
				ans.append(l[i - 1])
				inc = -1
				dec = 1
		ans.append(l[-1])
		print(len(ans))
		print(*ans)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__

def gift():
	for _ in range(t):
		n = int(input())
		arry = list(map(int, input().split()))
		ans = [arry[0]]
		pm = 'not'
		for i in range(n - 1):
			currele = arry[i + 1]
			prevele = arry[i]
			if pm == 'not':
				if currele > prevele:
					pm = 'plus'
				else:
					pm = 'minus'
			else:
				if currele > prevele:
					curpm = 'plus'
				else:
					curpm = 'minus'
				if curpm != pm:
					ans.append(arry[i])
					pm = curpm
			if i == n - 2:
				ans.append(arry[n - 1])
		yield len(ans)
		yield ' '.join((str(x) for x in ans))
t = int(input())
ans = gift()
print(*ans, sep='\n')


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	res = [arr[0]]
	for i in range(1, n - 1):
		if not (arr[i - 1] < arr[i] < arr[i + 1] or arr[i - 1] > arr[i] > arr[i + 1]):
			res.append(arr[i])
	res.append(arr[n - 1])
	print(len(res))
	for i in range(len(res)):
		print(res[i], end=' ')
	print()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import gcd, ceil

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[i - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans

def lcm(a, b):
	return a * b // gcd(a, b)

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
	n = int(input())
	a = list(map(int, input().split()))
	i = 0
	ans = []
	while i < n:
		try:
			j = i
			while j != n - 1 and a[j + 1] > a[j]:
				j += 1
			if j - i >= 2:
				ans += [a[i]]
				i = j
				continue
			j = i
			while j != n - 1 and a[j + 1] < a[j]:
				j += 1
			if j - i >= 2:
				ans += [a[i]]
				i = j
				continue
			ans += [a[i]]
			i += 1
		except:
			ans += [a[i]]
			i += 1
	print(len(ans))
	print(*ans)


t = int(input())
for test in range(t):
	n = int(input())
	p = [int(i) for i in input().split()]
	ans = [p[0]]
	pre = p[1] - p[0]
	if pre > 0:
		pre = 1
	elif pre < 0:
		pre = -1
	for it in range(2, n):
		si = p[it] - p[it - 1]
		if pre == 0:
			if si != 0 and it == n - 1:
				ans.append(p[it])
			pre = si
		else:
			if si * pre < 0:
				ans.append(p[it - 1])
				pre = si
			if it == n - 1:
				ans.append(p[it])
	if len(ans) == 1:
		ans = [p[0], p[1]]
	print(len(ans))
	print(' '.join([str(i) for i in ans]))


from collections import Counter
from collections import defaultdict
from collections import deque
import math
import heapq
import sys
import io, os
input = sys.stdin.readline
from bisect import *
rs = lambda : input().strip()
ri = lambda : int(input())
rl = lambda : list(map(int, input().split()))
rls = lambda : list(map(str, input().split()))
t = int(input())
for _ in range(0, t):
	n = int(input())
	a = rl()
	c = 1
	ans = []
	d = 0
	for i in range(0, n):
		if i == 0:
			ans.append(a[i])
			prev = a[i]
		elif i == 1:
			if a[i] > a[i - 1]:
				d = 1
				prev = a[i]
			if a[i] < a[i - 1]:
				d = -1
				prev = a[i]
		elif d == 1 and prev < a[i]:
			prev = a[i]
		elif d == -1 and prev > a[i]:
			prev = a[i]
		elif d == 1 and prev > a[i]:
			ans.append(prev)
			prev = a[i]
			d = -1
		elif d == -1 and prev < a[i]:
			ans.append(prev)
			prev = a[i]
			d = 1
	ans.append(a[n - 1])
	print(len(ans))
	print(*ans)


import sys
import math
input = sys.stdin.readline
from collections import deque
from queue import LifoQueue

def binary_search(a, n):
	L = 0
	R = len(a) - 1
	while L <= R:
		mid = L + (R - L) // 2
		if a[mid] == n:
			return mid
		elif a[mid] < n:
			L = mid + 1
		else:
			R = mid - 1
	return -1
for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [p[0]]
	if p[0] < p[1]:
		fl = True
	else:
		fl = False
	for i in range(n - 1):
		if fl:
			if p[i] > p[i + 1]:
				ans.append(p[i])
				fl = False
		elif p[i] < p[i + 1]:
			ans.append(p[i])
			fl = True
	ans.append(p[-1])
	print(len(ans))
	print(*ans)


t = int(input())
for ii in range(t):
	n = int(input())
	p = [int(i) for i in input().split()]
	order = False
	if p[1] > p[0]:
		order = True
	ans = [p[0], p[1]]
	for i in range(1, n - 1):
		if p[i + 1] > p[i] and order == True:
			ans[-1] = p[i + 1]
		if p[i + 1] > p[i] and order == False:
			ans.append(p[i + 1])
			order = True
		if p[i + 1] < p[i] and order == False:
			ans[-1] = p[i + 1]
		if p[i + 1] < p[i] and order == True:
			ans.append(p[i + 1])
			order = False
	print(len(ans))
	print(*ans)


from sys import stdin, stdout
import sys
from math import *
for __ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	ans = [ar[0]]
	for i in range(1, n - 1):
		if ar[i - 1] < ar[i] > ar[i + 1]:
			ans.append(ar[i])
		elif ar[i - 1] > ar[i] < ar[i + 1]:
			ans.append(ar[i])
	ans.append(ar[-1])
	print(len(ans))
	print(*ans)


import os
import sys
from io import BytesIO, IOBase
from collections import Counter
from collections import deque
import heapq
import math
import statistics

def sin():
	return input()

def ain():
	return list(map(int, sin().split()))

def sain():
	return input().split()

def iin():
	return int(sin())
p = print
MAX = float('inf')
MIN = float('-inf')

def readTree(n):
	adj = [set() for _ in range(n)]
	for _ in range(n - 1):
		(u, v) = ain()
		adj[u - 1].add(v - 1)
		adj[v - 1].add(u - 1)
	return adj

def main():
	for _ in range(iin()):
		n = iin()
		l = ain()
		ans = [l[0]]
		prev = l[0]
		flag = 0
		for i in range(1, n):
			if flag == 0:
				if l[i] > prev:
					flag = 1
				else:
					flag = -1
			elif flag == 1:
				if l[i] > prev:
					prev = l[i]
				else:
					ans.append(prev)
					flag = -1
			elif l[i] < prev:
				prev = l[i]
			else:
				ans.append(prev)
				flag = 1
			prev = l[i]
		print(len(ans) + 1)
		print(*ans, l[-1])
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


import sys
input = sys.stdin.readline

def solve():
	N = int(input())
	ARR = list(map(int, input().split()))
	i = 0
	RESULT = []
	while i < N - 1:
		if ARR[i] < ARR[i + 1]:
			RESULT.append(ARR[i])
			while i < N - 1 and ARR[i] < ARR[i + 1]:
				i += 1
		else:
			RESULT.append(ARR[i])
			while i < N - 1 and ARR[i] > ARR[i + 1]:
				i += 1
	if RESULT[-1] != ARR[N - 1]:
		RESULT.append(ARR[N - 1])
	print(len(RESULT))
	print(*RESULT)
test = int(input())
for _ in range(test):
	solve()


t = int(input())
for _ in range(t):
	n = int(input())
	list1 = list(map(int, input().strip().split()))
	list2 = []
	list2.append(list1[0])
	for i in range(1, len(list1) - 1):
		if list1[i] > list1[i - 1] and list1[i] > list1[i + 1] or (list1[i] < list1[i - 1] and list1[i] < list1[i + 1]):
			list2.append(list1[i])
	list2.append(list1[n - 1])
	print(len(list2))
	for value in list2:
		print(value, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	r = [l[0]]
	for i in range(1, n - 1):
		if (l[i - 1] < l[i]) == (l[i] > l[i + 1]):
			r.append(l[i])
	r.append(l[-1])
	print(len(r))
	print(*r)


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = []
	dir = 1 if arr[1] - arr[0] > 0 else 0
	ans = [arr[0]]
	stack = [arr[1]]
	for j in range(2, n):
		if dir == 1:
			if stack[-1] < arr[j]:
				stack.pop()
				stack.append(arr[j])
			else:
				dir = 0
				ans.append(stack.pop())
				stack = [arr[j]]
		elif stack[-1] > arr[j]:
			stack.pop()
			stack.append(arr[j])
		else:
			dir = 1
			ans.append(stack.pop())
			stack = [arr[j]]
	ans.append(stack.pop())
	print(len(ans))
	print(*ans)


t = int(input())
for case in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	n2 = n
	new = [p[0]]
	for i in range(1, n - 1):
		num = p[i]
		if not (p[i - 1] < num < p[i + 1] or p[i + 1] < num < p[i - 1]):
			new.append(num)
		else:
			n2 -= 1
	new.append(p[n - 1])
	print(n2)
	print(' '.join([str(i) for i in new]))


import sys

def rs():
	return sys.stdin.readline().rstrip()

def ri():
	return int(sys.stdin.readline())

def ria():
	return list(map(int, sys.stdin.readline().split()))

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')

def solve(n, p):
	res = [p[0]]
	d = 1 if p[1] > p[0] else -1
	i = 0
	while i < n - 1:
		j = i + 1
		while j < n and p[i] * d < p[j] * d:
			i = j
			j += 1
		res.append(p[j - 1])
		d = -d
	wi(len(res))
	wia(res)

def main():
	for _ in range(ri()):
		n = ri()
		p = ria()
		solve(n, p)
main()


def solve(n, ar):
	track = [ar[0]]
	for i in range(1, n):
		if i == n - 1:
			continue
		if ar[i] - ar[i - 1] > 0 and ar[i + 1] - ar[i] > 0:
			continue
		elif ar[i] - ar[i - 1] < 0 and ar[i + 1] - ar[i] < 0:
			continue
		else:
			track.append(ar[i])
	track.append(ar[n - 1])
	print(len(track))
	print(' '.join(map(str, track)))
t = int(input())
for _ in range(t):
	n = int(input())
	perm = list(map(int, input().split()))
	solve(n, perm)


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	arr1 = [arr[0]]
	for i in range(1, n - 1):
		if arr[i] >= arr[i - 1] and arr[i] <= arr[i + 1]:
			pass
		elif arr[i] <= arr[i - 1] and arr[i] >= arr[i + 1]:
			pass
		else:
			arr1.append(arr[i])
	arr1.append(arr[n - 1])
	print(len(arr1))
	print(*arr1)


from sys import stdin, stdout
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	arr = list(map(int, stdin.readline().strip().split()))
	l = False
	m = False
	raj = [arr[0]]
	for i in range(1, n):
		if i == 1 and raj[0] != arr[i]:
			raj.append(arr[i])
			if arr[i] > raj[0]:
				m = True
			else:
				l = True
		elif arr[i] > raj[-1] and m:
			raj.pop()
			raj.append(arr[i])
			m = True
		elif arr[i] < raj[-1] and l:
			raj.pop()
			raj.append(arr[i])
			l = True
		elif arr[i] != raj[-1]:
			raj.append(arr[i])
			l = not l
			m = not m
	print(len(raj))
	print(*raj)


import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def f():
	n = int(input())
	p = [int(s) for s in input().split()]
	inc = [0] * n
	for i in range(1, n):
		if p[i] > p[i - 1]:
			inc[i] = 1
	ans = [p[0]]
	for i in range(1, n - 1):
		if inc[i] != inc[i + 1] and p[i] != ans[-1]:
			ans.append(p[i])
	if p[n - 1] != ans[-1]:
		ans.append(p[n - 1])
	print(len(ans))
	print(' '.join((str(num) for num in ans)))
for _ in range(int(input())):
	f()


z = int(input())
for q in range(z):
	n = int(input())
	a = list(map(int, input().split()))
	x = [a[0]]
	for i in range(1, n - 1):
		if a[i] > a[i + 1] and a[i] > a[i - 1] or (a[i] < a[i + 1] and a[i] < a[i - 1]):
			x.append(a[i])
	x.append(a[n - 1])
	print(len(x))
	for i in range(len(x)):
		print(x[i], end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = [a[0]]
	if a[1] > a[0]:
		check = True
	else:
		check = False
	for i in range(1, n - 1):
		if a[i + 1] > a[i] and (not check):
			b.append(a[i])
			check = True
		elif a[i + 1] < a[i] and check:
			b.append(a[i])
			check = False
	if a[-1] != a[-2]:
		b.append(a[-1])
	print(len(b))
	for i in b:
		print(i, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	ans = []
	for i in range(len(a)):
		if i == 0 or i == n - 1:
			ans.append(a[i])
		else:
			if a[i - 1] > a[i] and a[i] > a[i + 1]:
				continue
			if a[i - 1] < a[i] and a[i] < a[i + 1]:
				continue
			ans.append(a[i])
	print(len(ans))
	print(*ans)


import sys
readline = sys.stdin.readline

def solve():
	N = int(readline())
	P = list(map(int, readline().split()))
	S = sum((abs(P[i] - P[i + 1]) for i in range(N - 1)))
	ans = [P[0]]
	for i in range(1, N):
		if P[i] == P[i - 1]:
			pass
		elif i > 1 and (P[i - 1] - P[i - 2]) * (P[i] - P[i - 1]) >= 0:
			ans[-1] = P[i]
		else:
			ans.append(P[i])
	print(len(ans))
	print(*ans)
T = int(readline())
for t in range(T):
	solve()


import sys
input = sys.stdin.readline
scan_int = lambda : int(input())
scan_string = lambda : input().rstrip()
read_list = lambda : list(read())
read = lambda : map(int, input().split())
read_float = lambda : map(float, input().split())

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

def gcd(a, b):
	if b == 0:
		return a
	return gcd(b, a % b)

def lcm(a, b):
	return a * b // math.gcd(a, b)

def is_integer(n):
	return math.ceil(n) == math.floor(n)

def nCr(n, k):
	if k > n:
		return 0
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

def power(x, y, p):
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

def sieve(n):
	prime = [True for i in range(n + 1)]
	(prime[0], prime[1]) = (False, False)
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	return prime

def phi(n):
	result = n
	p = 2
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			result = result * (1.0 - 1.0 / float(p))
		p = p + 1
	if n > 1:
		result = result * (1.0 - 1.0 / float(n))
	return int(result)

def is_prime(n):
	if n == 0:
		return False
	if n == 1:
		return True
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True

def next_prime(n, primes):
	while primes[n] != True:
		n += 1
	return n
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
	res = []
	for i in range(2, int(x ** 0.5) + 1):
		while x % i == 0:
			res.append(i)
			x //= i
	if x != 1:
		res.append(x)
	return res

def factors(n):
	res = []
	for i in range(1, int(n ** 0.5) + 1):
		if n % i == 0:
			res.append(i)
			res.append(n // i)
	return list(set(res))

def int_array():
	return list(map(int, input().strip().split()))

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()

def binary_search(low, high, w, h, n):
	while low < high:
		mid = low + (high - low) // 2
		if check(mid, w, h, n):
			low = mid + 1
		else:
			high = mid
	return low

def check(beauty, s, n, count):
	pass
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
from itertools import permutations
import math
import bisect as bis
import random
import sys

def solve():
	n = scan_int()
	a = read_list()
	ans = [a[0]]
	for i in range(1, n - 1):
		if a[i - 1] < a[i] and a[i + 1] < a[i]:
			ans.append(a[i])
		elif a[i - 1] > a[i] and a[i + 1] > a[i]:
			ans.append(a[i])
	ans.append(a[-1])
	print(len(ans))
	print(*ans)
for _ in range(int(input())):
	solve()


from sys import stdin, stdout

def isValley(i, x):
	return x[i] < x[i + 1] and x[i] < x[i - 1]

def isPeek(i, x):
	return x[i] > x[i + 1] and x[i] > x[i - 1]

def main():
	t = int(stdin.readline())
	ans = [[] for i in range(t)]
	for q in range(t):
		n = int(stdin.readline())
		a = [int(x) for x in stdin.readline().split()]
		peek = a[1]
		valley = a[1]
		ans[q].append(a[0])
		for i in range(1, n - 1):
			if isPeek(i, a) or isValley(i, a):
				ans[q].append(a[i])
		ans[q].append(a[-1])
	for i in range(t):
		print(len(ans[i]))
		print(*ans[i])
main()


t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(x) for x in input().split()]
	visited = [False for x in range(n)]
	count = n
	for i in range(1, n - 1):
		if arr[i - 1] < arr[i] < arr[i + 1]:
			visited[i] = True
			count -= 1
		if arr[i - 1] > arr[i] > arr[i + 1]:
			visited[i] = True
			count -= 1
	print(count)
	for (i, each) in enumerate(visited):
		if not each:
			print(arr[i], end=' ')
	print()


t = int(input())
for q in range(t):
	n = int(input())
	mas = list(map(int, input().split()))
	ans = [0]
	f1 = 0
	f2 = 1
	for i in range(2, n):
		if mas[f1] < mas[f2]:
			if mas[f2] > mas[i]:
				ans.append(f2)
				f1 = f2
		elif mas[f2] < mas[i]:
			ans.append(f2)
			f1 = f2
		f2 = i
	ans.append(f2)
	print(len(ans))
	for i in ans:
		print(mas[i], end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	prev = None
	ans = []
	for i in range(1, n):
		if p[i] > p[i - 1] and prev != 1:
			prev = 1
			ans.append(p[i - 1])
		elif p[i] < p[i - 1] and prev != -1:
			prev = -1
			ans.append(p[i - 1])
	ans.append(p[-1])
	print(len(ans))
	print(' '.join(map(str, ans)))


t = int(input())
ans = []
for x in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	q = p[:]
	start = 0
	subs = []
	for y in range(1, n - 1):
		if p[y] < p[y + 1] and p[y] > p[y - 1]:
			q[y] = 0
		if p[y] > p[y + 1] and p[y] < p[y - 1]:
			q[y] = 0
	for y in range(n):
		if q[y] != 0:
			subs.append(q[y])
	ans.append(subs)
for a in ans:
	print(len(a))
	for s in a:
		print(s, end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	a = [int(s) for s in input().split()]
	b = [a[0]]
	flag = 0
	for i in range(1, n):
		if a[i] > a[i - 1]:
			if flag == -1:
				b.append(a[i - 1])
			flag = 1
		elif a[i] < a[i - 1]:
			if flag == 1:
				b.append(a[i - 1])
			flag = -1
	if a[n - 2] != a[n - 1]:
		b.append(a[n - 1])
	print(len(b))
	print(*b)


import sys
from sys import maxsize
from collections import Counter as cnt
from collections import defaultdict as dic
get_int = lambda : int(input())
get_list = lambda : list(map(int, input().rstrip().split()))
TEST_CASES = True

def main():
	n = get_int()
	a = get_list()
	j = 1
	while j < len(a) - 1:
		if a[j - 1] < a[j] < a[j + 1] or a[j - 1] > a[j] > a[j + 1]:
			del a[j]
		else:
			j += 1
	print(len(a))
	print(*a)
if not TEST_CASES:
	main()
else:
	[main() for _ in range(int(input()))]


from sys import stdin, stdout
from sys import maxsize

def solve(a, n):
	b = [a[0]]
	for i in range(1, n - 1):
		if a[i - 1] < a[i] and a[i + 1] < a[i] or (a[i - 1] > a[i] and a[i + 1] > a[i]):
			b.append(a[i])
	b.append(a[-1])
	return b
test = 1
test = int(input())
for t in range(0, test):
	n = int(input())
	arr = [int(x) for x in input().split()]
	ans = solve(arr, n)
	print(len(ans))
	for a in ans:
		print(a, end=' ')
	print()


import sys
input = sys.stdin.buffer.readline

def prog():
	for _ in range(int(input())):
		n = int(input())
		array = list(map(int, input().split()))
		remove = set()
		up = False
		down = False
		if array[1] > array[0]:
			up = True
		else:
			down = True
		for i in range(2, n):
			if up:
				if array[i] > array[i - 1]:
					remove.add(i - 1)
				else:
					up = False
					down = True
			elif down:
				if array[i] < array[i - 1]:
					remove.add(i - 1)
				else:
					down = False
					up = True
		output = []
		for i in range(n):
			if i not in remove:
				output.append(str(array[i]))
		sys.stdout.write(str(n - len(remove)) + '\n')
		sys.stdout.write(' '.join(output) + '\n')
prog()


t = int(input())
for q in range(t):
	n = int(input())
	mass = [int(x) for x in input().split()]
	answer = [mass[0]]
	ind = 0
	for i in range(1, n - 1):
		if mass[i] > mass[i - 1] and mass[i] > mass[i + 1] or (mass[i] < mass[i - 1] and mass[i] < mass[i + 1]):
			answer.append(mass[i])
			ind = i
	answer.append(mass[-1])
	print(len(answer))
	print(*answer)


import sys
sys.setrecursionlimit(10000)
t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	prev = p[1]
	major = [p[0], p[1]]
	ismin = True
	if p[1] > p[0]:
		ismin = False
	for no in p[2:]:
		if no < prev and ismin is True:
			del major[-1]
			major.append(no)
		elif no > prev and ismin is True:
			major.append(no)
			ismin = False
		elif no < prev and ismin is False:
			major.append(no)
			ismin = True
		elif no > prev and ismin is False:
			del major[-1]
			major.append(no)
		prev = no
	print(len(major))
	print(*major)


import sys
import bisect as b
import math
from collections import defaultdict as dd
input = sys.stdin.readline
mo = 10 ** 9 + 7

def cin():
	return map(int, sin().split())

def ain():
	return list(map(int, sin().split()))

def sin():
	return input()

def inin():
	return int(input())

def pref(a, n):
	pre = [0] * n
	pre[0] = a[0]
	for i in range(1, n):
		pre[i] = a[i] + pre[i - 1]
	return pre
for _ in range(inin()):
	n = inin()
	l = ain()
	s = 1
	f = f1 = 0
	st = l[0]
	ans = []
	for i in range(0, n - 1):
		if l[i + 1] > l[i]:
			if f == 0:
				ans += [st]
				s += 1
			f = 1
			f1 = 0
			st = l[i + 1]
		elif l[i + 1] < l[i]:
			if f1 == 0:
				ans += [st]
				s += 1
			st = l[i + 1]
			f1 = 1
			f = 0
	print(s)
	x = ans + [st]
	print(*x)


import sys
from collections import defaultdict as dd
from collections import deque
from fractions import Fraction as f

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
from math import *
import copy
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def li():
	return [int(x) for x in input().split()]

def fi():
	return int(input())

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def bo(i):
	return ord(i) - ord('a')
from copy import *
from bisect import *
from itertools import permutations
t = fi()
while t > 0:
	t -= 1
	n = fi()
	a = li()
	i = 1
	c = 0
	d = [a[0]]
	flag = 0
	while i < n:
		j = i - 1
		if a[i] > a[i - 1]:
			while i < n and a[i] > a[i - 1]:
				i += 1
			d.append(a[i - 1])
			c += abs(a[i - 1] - a[j])
		elif a[i] < a[i - 1]:
			while i < n and a[i] < a[i - 1]:
				i += 1
			d.append(a[i - 1])
			c += abs(a[i - 1] - a[j])
		else:
			i += 1
		if flag:
			break
	print(len(d))
	print(*d)


wer = int(input())
for ewr in range(wer):
	n = int(input())
	li = list(map(int, input().split(' ')))
	i = 1
	r = 0
	while True:
		if i + 1 >= len(li):
			break
		elif li[i - 1] < li[i] < li[i + 1] or li[i - 1] > li[i] > li[i + 1]:
			li[i] = li[i - 1]
			r += 1
		else:
			i += 1
	print(len(li) - r)
	print(li[0], end=' ')
	for i in range(1, len(li)):
		if li[i] != li[i - 1]:
			print(li[i], end=' ')
	print('')


for _ in range(int(input())):
	n = int(input())
	arr = [int(i) for i in input().split()]
	sub = [arr[0]]
	if arr[1] > sub[0]:
		big = True
	else:
		big = False
	pos = arr[0]
	for i in range(1, n):
		if arr[i] > pos and big:
			pos = arr[i]
		elif arr[i] < pos and (not big):
			pos = arr[i]
		elif arr[i] < pos and big:
			sub.append(pos)
			pos = arr[i]
			big = False
		elif arr[i] > pos and (not big):
			sub.append(pos)
			pos = arr[i]
			big = True
	sub.append(pos)
	print(len(sub))
	print(*sub)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = [a[0]]
	for i in range(1, n - 1):
		if a[i] > a[i - 1] and a[i] > a[i + 1]:
			b.append(a[i])
		elif a[i] < a[i - 1] and a[i] < a[i + 1]:
			b.append(a[i])
	b.append(a[n - 1])
	print(len(b))
	print(*b)


from sys import stdin, stdout
for test in range(int(stdin.readline())):
	n = int(stdin.readline())
	arr = [int(x) for x in stdin.readline().split()]
	dp = [arr[0]]
	ans = 1
	for i in range(1, n - 1):
		if arr[i] < min(arr[i - 1], arr[i + 1]) or arr[i] > max(arr[i - 1], arr[i + 1]):
			dp.append(arr[i])
			ans += 1
	print(ans + 1)
	dp.append(arr[-1])
	print(*dp, sep=' ')


def peak(i, l):
	if l[i] > l[i - 1] and l[i] > l[i + 1]:
		return True
	if l[i] < l[i - 1] and l[i] < l[i + 1]:
		return True
	return False
from collections import defaultdict
for _ in range(int(input())):
	d = defaultdict(int)
	check = defaultdict(int)
	n = int(input())
	l = list(map(int, input().split()))
	k = [l[0]]
	for i in range(1, len(l) - 1):
		if peak(i, l):
			k.append(l[i])
	print(len(k) + 1)
	print(*k + [l[-1]])


import sys
for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = []
	ans.append(l[0])
	for i in range(1, len(l) - 1):
		if l[i - 1] < l[i] and l[i] > l[i + 1]:
			ans.append(l[i])
		if l[i - 1] > l[i] and l[i + 1] > l[i]:
			ans.append(l[i])
	ans.append(l[n - 1])
	print(len(ans))
	for i in ans:
		print(i, end=' ')
	print('')


import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [p[0]]
	sign = ''
	val = p[1]
	if val > p[0]:
		sign = '+'
	else:
		sign = '-'
	for i in range(2, n):
		if sign == '+':
			if p[i] > val:
				val = p[i]
			else:
				ans.append(val)
				val = p[i]
				sign = '-'
		elif val > p[i]:
			val = p[i]
		else:
			ans.append(val)
			val = p[i]
			sign = '+'
	ans.append(val)
	print(len(ans))
	print(*ans)


list_ans = []
for _ in range(int(input())):
	n = int(input())
	list1 = list(map(int, input().split()))
	list2 = [list1[0]]
	for i in range(1, n - 1):
		if (list1[i] - list1[i - 1]) * (list1[i + 1] - list1[i]) < 0 or list1[i - 1] == list1[i] != list1[i + 1]:
			list2.append(list1[i])
	list2.append(list1[-1])
	list_ans.append(len(list2))
	list_ans.append(' '.join(map(str, list2)))
print(*list_ans, sep='\n')


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = [a[0]] + [a[i] for i in range(1, n - 1) if not (a[i - 1] < a[i] < a[i + 1] or a[i - 1] > a[i] > a[i + 1])] + [a[-1]]
	print(len(b))
	print(*b)


t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	j = 0
	s = set()
	s.add(0)
	while j < len(l) - 1:
		while j < len(l) - 1 and l[j] > l[j + 1]:
			j += 1
		s.add(j)
		while j < len(l) - 1 and l[j] < l[j + 1]:
			j += 1
		s.add(j)
	s.add(len(l) - 1)
	sum = 0
	print(len(s))
	for element in sorted(s):
		print(l[element], end=' ')


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().rstrip().split(' ')))
	if l[0] - l[1] < 0:
		dir = False
	else:
		dir = True
	r = [l[0], l[1]]
	for i in range(2, n):
		if dir:
			if l[i] - r[-1] > 0:
				r.append(l[i])
				dir = False
			else:
				r[-1] = l[i]
		elif l[i] - r[-1] < 0:
			r.append(l[i])
			dir = True
		else:
			r[-1] = l[i]
	print(len(r))
	print(*r)


from sys import stdin, stdout
import math, queue, heapq
fastinput = stdin.readline
fastout = stdout.write
t = int(fastinput())
while t:
	t -= 1
	n = int(fastinput())
	b = list(map(int, fastinput().split()))
	ans = [b[0], b[1]]
	for i in b[2:]:
		x1 = ans.pop()
		x2 = ans.pop()
		if x1 - x2 > 0 and i - x1 > 0:
			ans.append(x2)
			ans.append(i)
		elif x1 - x2 < 0 and i - x1 < 0:
			ans.append(x2)
			ans.append(i)
		else:
			ans.append(x2)
			ans.append(x1)
			ans.append(i)
	print(len(ans))
	print(*ans)


from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
abd = {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('a')

def solve():
	for _ in range(ii()):
		n = ii()
		a = li()
		ans = [a[0]]
		f = 0
		if a[1] > a[0]:
			f = 1
			x = a[1]
		else:
			x = a[1]
		for i in range(2, n):
			if f == 0:
				if a[i] > x:
					ans.append(x)
					x = a[i]
					f = 1
				else:
					x = a[i]
			elif a[i] < x:
				ans.append(x)
				x = a[i]
				f = 0
			else:
				x = a[i]
		ans.append(x)
		print(len(ans))
		print(*ans)
solve()


for cas in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	updown = a[1] - a[0] > 0
	ret = [a[0]]
	for i in range(2, n):
		if updown != (a[i] - a[i - 1] > 0):
			ret.append(a[i - 1])
			updown ^= 1
	ret.append(a[n - 1])
	print(len(ret))
	print(*ret)


import atexit
import io
import sys
import math
from collections import defaultdict, Counter
t = int(input())
for i in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	total = abs(p[0] - p[1])
	a = [p[0], p[1]]
	for j in range(2, n):
		now = total + abs(p[j] - a[-1])
		if abs(p[j] - a[-2]) >= abs(p[j] - a[-1]) + abs(a[-1] - a[-2]):
			total -= abs(a[-1] - a[-2])
			total += abs(p[j] - a[-2])
			a.pop()
			a.append(p[j])
		else:
			total = now
			a.append(p[j])
	print(len(a))
	print(*a)


n = int(input())
for _ in range(n):
	t = int(input())
	li = [int(k) for k in input().split()]
	ans = []
	m = len(li)
	for i in range(len(li)):
		if i == 0 or i == m - 1:
			ans.append(li[i])
		elif li[i] > li[i + 1] and li[i] > li[i - 1] or (li[i] < li[i + 1] and li[i] < li[i - 1]):
			ans.append(li[i])
	print(len(ans))
	for i in ans:
		print(i, end=' ')


t = int(input())
for s in range(t):
	n = int(input())
	array = list(map(int, input().split()))
	add = 0
	rama = []
	for i in range(1, n):
		rama.append(array[i] - array[i - 1])
	rama.append(0)
	shiv = [array[0]]
	for i in range(n - 1):
		if rama[i] > 0 and rama[i + 1] <= 0:
			shiv.append(array[i + 1])
			add += 1
		elif rama[i] < 0 and rama[i + 1] >= 0:
			shiv.append(array[i + 1])
			add += 1
	print(add + 1)
	for i in shiv:
		print(i, end=' ')
	print()


from math import inf as inf
from math import *
from collections import *
import sys
from itertools import permutations
input = sys.stdin.readline
t = int(input())
while t:
	t -= 1
	n = int(input())
	a = list(map(int, input().split()))
	r = [a[0]]
	for i in range(1, n - 1):
		if abs(a[i] - a[i - 1]) + abs(a[i] - a[i + 1]) == abs(a[i - 1] - a[i + 1]):
			continue
		r.append(a[i])
	r.append(a[-1])
	print(len(r))
	print(*r)


for _ in range(int(input())):
	n = int(input())
	stos = []
	T = [0]
	T += list(map(int, input().split()))
	for i in range(1, n + 1):
		a = T[i]
		while len(stos) >= 2 and (a > stos[-1] and stos[-1] > stos[-2] or (a < stos[-1] and stos[-1] < stos[-2])):
			stos.pop()
		stos.append(a)
	print(len(stos))
	print(' '.join(map(str, stos)))


import sys
fast_reader = sys.stdin.readline
fast_writer = sys.stdout.write

def input():
	return fast_reader().strip()

def list_input():
	return list(map(int, input().split()))

def sep_input():
	return map(int, input().split())
for _ in range(int(input())):
	n = int(input())
	l = list_input()
	ans = 1
	a = []
	if l[0] < l[1]:
		f = 1
		a.append(l[0])
	else:
		f = 0
		a.append(l[0])
	for i in range(1, n - 1):
		if f == 1 and l[i] > l[i + 1]:
			ans += 1
			a.append(l[i])
			f = 0
		elif f == 0 and l[i] < l[i + 1]:
			ans += 1
			a.append(l[i])
			f = 1
	a.append(l[-1])
	ans += 1
	print(ans)
	print(*a)


def intJoin(arr):
	return ' '.join([str(i) for i in arr])

def peakFind(arr):
	peaks = [arr[0]]
	for i in range(1, len(arr) - 1):
		three = [arr[i - 1], arr[i], arr[i + 1]]
		if max(three) == arr[i] or min(three) == arr[i]:
			peaks.append(arr[i])
	peaks.append(arr[-1])
	return peaks

def answer(arr):
	peaks = peakFind(arr)
	print(len(peaks))
	print(intJoin(peaks))
testCount = int(input())
for _ in range(testCount):
	n = int(input())
	arr = list(map(int, input().split()))
	answer(arr)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x - 1)

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = 0
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = 1
			break
	return ans

def sieve_of_eratosthenes(n):
	ans = []
	arr = [1] * (n + 1)
	(arr[0], arr[1], i) = (0, 0, 2)
	while i * i <= n:
		if arr[i] == 1:
			j = i + i
			while j <= n:
				arr[j] = 0
				j += i
		i += 1
	for k in range(n):
		if arr[k] == 1:
			ans.append(k)
	return ans

def nc2(x):
	if x == 1:
		return 0
	else:
		return x * (x - 1) // 2
for _ in range(int(input())):
	n = int(input())
	num = list(map(int, input().split()))
	ans = [num[0]]
	for i in range(1, n - 1):
		if num[i - 1] < num[i] > num[i + 1] or num[i - 1] > num[i] < num[i + 1]:
			ans.append(num[i])
	ans.append(num[-1])
	print(len(ans))
	print(*ans)


import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	n = Int()
	a = array()
	status = [[0, 0] for i in range(n)]
	for i in range(1, n - 1):
		if a[i - 1] > a[i]:
			status[i][0] = -1
		else:
			status[i][0] = 1
		if a[i + 1] > a[i]:
			status[i][1] = -1
		else:
			status[i][1] = 1
	ans = []
	for i in range(n):
		if status[i][0] == status[i][1]:
			ans.append(a[i])
	print(len(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	ans = [l[0]]
	now = 0
	count = l[0]
	for i in l[1:]:
		if now == 0:
			if i > count:
				now = 1
			else:
				now = -1
		elif now == 1:
			if i < count:
				ans.append(count)
				now = -1
		elif now == -1:
			if i > count:
				ans.append(count)
				now = 1
		count = i
	ans.append(l[-1])
	print(len(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	(i, j) = (0, 1)
	elements = []
	direction = int(abs(p[j] - p[i]) / (p[j] - p[i]))
	while j < n:
		if j == n - 1:
			elements.append(p[i])
			elements.append(p[j])
			break
		newdir = int(abs(p[j + 1] - p[j]) / (p[j + 1] - p[j]))
		if newdir != direction:
			elements.append(p[i])
			i = j
		j += 1
		direction = newdir
	print(len(elements))
	for e in elements:
		print(e, end=' ')
	print()


def inp():
	return map(int, input().split())
for _ in range(int(input())):
	n = int(input())
	a = list(inp())
	x = a[0]
	res = [a[0]]
	for i in range(1, n - 1):
		if x < a[i] < a[i + 1] or x > a[i] > a[i + 1]:
			continue
		x = a[i]
		res.append(a[i])
	res.append(a[-1])
	print(len(res))
	print(*res)


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split()))
	l = [arr[0]]
	sign = 0
	for i in range(1, n):
		if sign == 0:
			if arr[i] > l[-1]:
				sign = 1
			else:
				sign = -1
			l += [arr[i]]
		elif sign == 1:
			if arr[i] > l[-1]:
				l[-1] = arr[i]
			else:
				l += [arr[i]]
				sign = -1
		elif sign == -1:
			if arr[i] < l[-1]:
				l[-1] = arr[i]
			else:
				l += [arr[i]]
				sign = 1
	print(len(l))
	print(*l)


def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		a = list(map(int, input().split()))
		b = [0] * n
		b[0] = b[n - 1] = 1
		ans = []
		s = 0
		for i in range(1, n - 1):
			if a[i - 1] < a[i] > a[i + 1]:
				b[i] = 1
			elif a[i - 1] > a[i] < a[i + 1]:
				b[i] = 1
		for i in range(n):
			if b[i] == 1:
				ans.append(a[i])
		print(len(ans))
		for i in ans:
			print(i, end=' ')
		print()
main()


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	if l[0] < l[1]:
		f = 1
	else:
		f = 0
	ans = [l[0]]
	for i in range(1, n):
		if f == 0:
			if l[i - 1] >= l[i]:
				continue
			else:
				f = 1
				ans.append(l[i - 1])
		elif l[i - 1] < l[i]:
			continue
		else:
			f = 0
			ans.append(l[i - 1])
	ans.append(l[n - 1])
	print(len(ans))
	print(*ans, sep=' ')


t = int(input())
for _ in range(t):
	n = int(input())
	lis = list(map(int, input().split()))
	ans = []
	a = lis[0]
	ans.append(a)
	flag = 0
	if lis[1] > a:
		flag = 1
	else:
		flag = -1
	for i in range(1, n - 1):
		if flag == 1:
			if lis[i + 1] > lis[i]:
				continue
			else:
				ans.append(lis[i])
				a = lis[i]
				flag = -1
				continue
		if flag == -1:
			if lis[i + 1] < lis[i]:
				continue
			else:
				ans.append(lis[i])
				a = lis[i]
				flag = 1
				continue
	ans.append(lis[-1])
	print(len(ans))
	print(*ans, sep=' ')


def task_B():
	t = int(input())
	for _ in range(t):
		n = int(input())
		array = list(map(int, input().split()))
		all_sum = 0
		ans = []
		ans.append(array[0])
		for i in range(1, n - 1):
			if ans[-1] <= array[i] <= array[i + 1] or ans[-1] >= array[i] >= array[i + 1]:
				continue
			else:
				ans.append(array[i])
		ans.append(array[-1])
		print(len(ans))
		print(' '.join(map(str, ans)))

def main():
	task_B()
main()


for i in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	b = []
	b.append(a[0])
	for i in range(1, n - 1):
		if a[i] > a[i - 1] and a[i] > a[i + 1] or (a[i] < a[i - 1] and a[i] < a[i + 1]):
			b.append(a[i])
	b.append(a[-1])
	print(len(b))
	for i in b:
		print(i, end=' ')


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	k = [a[0]]
	for i in range(n - 1):
		if a[i] != a[i + 1]:
			k.append(a[i + 1])
	n = len(k)
	l = [a[0]]
	for i in range(n - 2):
		if not (k[i] <= k[i + 1] <= k[i + 2] or k[i] >= k[i + 1] >= k[i + 2]):
			l.append(k[i + 1])
	l.append(k[-1])
	print(len(l))
	print(*l)


import math
t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	res = [l[0]]
	for i in range(1, n - 1):
		if l[i - 1] < l[i] and l[i + 1] < l[i]:
			res.append(l[i])
		elif l[i - 1] > l[i] and l[i + 1] > l[i]:
			res.append(l[i])
	res.append(l[n - 1])
	print(len(res))
	print(*res)


for _ in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()]
	s = [a[0]]
	for i in range(1, n - 1):
		if a[i] > a[i - 1] and a[i + 1] < a[i]:
			s.append(a[i])
		if a[i] < a[i - 1] and a[i + 1] > a[i]:
			s.append(a[i])
	s.append(a[-1])
	print(len(s))
	print(*s)


from sys import *
input = stdin.readline
for u in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	d = [l[0]]
	i = 1
	while i < n:
		if l[i] > l[i - 1]:
			while i < n and l[i] > l[i - 1]:
				i = i + 1
			i = i - 1
			d.append(l[i])
		else:
			while i < n and l[i] < l[i - 1]:
				i = i + 1
			i = i - 1
			d.append(l[i])
		i += 1
	print(len(d))
	print(*d)


for _ in range(int(input())):
	n = int(input())
	ar = list(map(int, input().split()))
	li = [ar[0], ar[1]]
	for i in range(2, n):
		if (ar[i] - li[-1]) * (li[-1] - li[-2]) >= 0:
			li[-1] = ar[i]
		else:
			li.append(ar[i])
	print(len(li))
	print(*li)


t = int(input())
for i in range(t):
	n = int(input())
	c = list(map(int, input().split()))
	a = []
	a.append(c[0])
	for i in range(n - 1):
		if c[i] != c[i + 1]:
			a.append(c[i + 1])
	b = []
	last = 0
	b.append(a[0])
	for i in range(len(a) - 1):
		if last < 0 and a[i + 1] - a[i] > 0:
			b.append(a[i])
		elif last > 0 and a[i + 1] - a[i] < 0:
			b.append(a[i])
		if a[i + 1] - a[i] > 0:
			last = 1
		else:
			last = -1
	b.append(a[-1])
	print(len(b))
	print(*b)


def function(length):
	something = []
	for i in range(1, length - 1):
		if array[i + 1] <= array[i] >= array[i - 1] or array[i + 1] >= array[i] <= array[i - 1]:
			something.append(array[i])
	something = [array[0]] + something + [array[length - 1]]
	return something
for i in range(int(input())):
	length = int(input())
	array = [int(x) for x in input().split()]
	print(len(function(length)))
	print(*function(length))


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	n = int(input())
	P = list(map(int, input().split()))
	A = [P[0]]
	for i in range(1, n - 1):
		if P[i] < P[i - 1] and P[i] < P[i + 1]:
			A.append(P[i])
		if P[i] > P[i - 1] and P[i] > P[i + 1]:
			A.append(P[i])
	A.append(P[-1])
	print(len(A))
	print(*A)


import sys
t = int(sys.stdin.readline())
while t:
	n = int(sys.stdin.readline())
	arr = list(map(int, input().split()))
	stack = [arr[0], arr[1]]
	for i in range(2, n):
		if abs(stack[-1] - stack[-2]) + abs(arr[i] - stack[-1]) > abs(stack[-2] - arr[i]):
			stack.append(arr[i])
		else:
			stack.pop()
			stack.append(arr[i])
	print(len(stack))
	print(*stack)
	t -= 1


def read_ints():
	return list(map(int, input().split()))
t = int(input())
for i in range(t):
	(n,) = read_ints()
	p = read_ints()
	si = [0]
	i = 0
	while i < n:
		inc = p[i + 1] > p[i]
		for j in range(i + 1, n):
			if (p[j] > p[j - 1]) != inc:
				i = j - 1
				si.append(i)
				break
		else:
			break
	si.append(-1)
	print(len(si))
	print(*[p[j] for j in si])


from sys import *
from math import *
from bisect import *
t = int(stdin.readline())
for _ in range(t):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().split()))
	ans = [a[0]]
	for i in range(1, n - 1):
		if a[i] > a[i - 1] and a[i] > a[i + 1]:
			ans.append(a[i])
		elif a[i] < a[i - 1] and a[i] < a[i + 1]:
			ans.append(a[i])
	ans.append(a[n - 1])
	print(len(ans))
	print(*ans)


import sys, os
from io import BytesIO, IOBase
import collections, itertools, bisect, heapq, math, string
from decimal import *
BUFSIZE = 8192
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def main():
	t = int(input())
	for i in range(t):
		n = int(input())
		p = list(map(int, input().split()))
		f = True if p[1] > p[0] else False
		ans = [p[0], p[1]]
		for j in range(2, n):
			temp = True if p[j] > ans[-1] else False
			if temp == f:
				ans.pop(-1)
			else:
				f = temp
			ans.append(p[j])
		print(len(ans))
		print(' '.join([str(x) for x in ans]))
main()


for t in range(int(input())):
	n = int(input())
	p = [int(i) for i in input().split()]
	ans = [str(p[0])]
	i = 1
	while i + 1 < n:
		if p[i - 1] < p[i] > p[i + 1] or p[i - 1] > p[i] < p[i + 1]:
			ans.append(str(p[i]))
		i += 1
	ans.append(str(p[-1]))
	print(len(ans))
	print(' '.join(ans))


from sys import stdin, stdout
from math import gcd, sqrt
from collections import deque
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
P = lambda x: stdout.write(x)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
mx = 10 ** 7 + 1
for _ in range(I()):
	n = I()
	a = list(R())
	m = a.copy()
	ln = n
	for i in range(1, n - 1):
		if a[i - 1] < a[i + 1] and a[i - 1] < a[i] < a[i + 1]:
			m[i] = 0
			ln -= 1
		elif a[i - 1] > a[i + 1] and a[i - 1] > a[i] > a[i + 1]:
			m[i] = 0
			ln -= 1
	print(ln)
	print(*[i for i in m if i])


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	diff = []
	for i in range(n - 1):
		diff.append(a[i + 1] - a[i])
	curr = False
	if diff[0] > 0:
		curr = True
	b = [a[0]]
	for i in range(1, n - 1):
		if diff[i] > 0 and (not curr):
			b.append(a[i])
			curr = True
		if diff[i] < 0 and curr:
			b.append(a[i])
			curr = False
	if a[-1] not in b:
		b.append(a[-1])
	print(len(b))
	print(' '.join([str(i) for i in b]))


from copy import *
from math import *
t = int(input())
for i in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	pp = [0]
	for j in range(len(l) - 2):
		if l[j + 1] > l[j] and l[j + 2] < l[j + 1]:
			pp.append(j + 1)
		if l[j + 1] < l[j] and l[j + 2] > l[j + 1]:
			pp.append(j + 1)
	pp.append(len(l) - 1)
	s = 0
	LMO = []
	for j in range(len(pp)):
		LMO.append(l[pp[j]])
	for j in range(len(LMO) - 1):
		s += abs(LMO[j + 1] - LMO[j])
	print(len(LMO))
	print(*LMO)


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	ind = 0
	ans = []
	for i in range(1, n):
		if p[i] > p[i - 1]:
			continue
		else:
			ans.append(p[ind])
			if ans[-1] != p[i - 1]:
				ans.append(p[i - 1])
			ind = i
	ans.append(p[ind])
	if ans[-1] != p[-1]:
		ans.append(p[-1])
	res = []
	ind = 0
	for i in range(1, len(ans)):
		if ans[i] < ans[i - 1]:
			continue
		else:
			res.append(ans[ind])
			if res[-1] != ans[i - 1]:
				res.append(ans[i - 1])
			ind = i
	res.append(ans[ind])
	if res[-1] != ans[-1]:
		res.append(ans[-1])
	print(len(res))
	print(*res)


for _ in range(int(input())):
	n = int(input())
	a = [int(j) for j in input().split()]
	result = [0]
	for i in range(1, n - 1):
		if a[i] > a[i - 1] and a[i] > a[i + 1] or (a[i] < a[i - 1] and a[i] < a[i + 1]):
			result.append(i)
	result.append(n - 1)
	print(len(result))
	print(*[a[elem] for elem in result])


cases = int(input())
for t in range(cases):
	n = int(input())
	p = list(map(int, input().split()))
	out = [p[0]]
	if p[1] >= p[0]:
		f = 0
	elif p[1] < p[0]:
		f = 1
	l = 2
	for i in range(1, n):
		if p[i] >= p[i - 1] and f == 1:
			out.append(p[i - 1])
			l += 1
			f = 0
		if p[i] < p[i - 1] and f == 0:
			out.append(p[i - 1])
			l += 1
			f = 1
	out.append(p[-1])
	print(l)
	print(*out)


import sys
reader = (s.rstrip() for s in sys.stdin)
input = reader.__next__
t = int(input())
for test in range(t):
	n = int(input())
	nums = [int(x) for x in input().split()]
	dir = 0
	delta = 0
	ans = 0
	start = nums[0]
	res = [nums[0]]
	if nums[1] >= nums[0]:
		dir = 1
	else:
		dir = -1
	for i in range(2, n):
		if dir == 1:
			if nums[i] >= nums[i - 1]:
				continue
			else:
				delta = nums[i - 1] - start
				ans += delta
				res.append(nums[i - 1])
				start = nums[i - 1]
				dir = -1
		elif nums[i] <= nums[i - 1]:
			continue
		else:
			delta = start - nums[i - 1]
			ans += delta
			start = nums[i - 1]
			dir = 1
			res.append(nums[i - 1])
	ans += abs(start - nums[n - 1])
	res.append(nums[n - 1])
	print(len(res))
	for i in range(len(res)):
		print(res[i], end=' ')
	print('')


def read_list():
	return list(map(int, input().split(' ')))

def print_list(l):
	print(' '.join(map(str, l)))
N = int(input())
for _ in range(N):
	n = int(input())
	a = read_list()
	res = [a[0], a[1]]
	for i in range(2, n):
		while len(res) > 1 and (a[i] >= res[-1] >= res[-2] or a[i] <= res[-1] <= res[-2]):
			res.pop()
		res.append(a[i])
	print(len(res))
	print_list(res)


INT_MAX = 10 ** 30 + 7
MOD = 10 ** 9 + 7

def INPUT():
	return list((int(i) for i in input().split()))

def LIST_1D_ARRAY(n):
	return [0 for _ in range(n)]

def LIST_2D_ARRAY(m, n):
	return [[0 for _ in range(n)] for _ in range(m)]
import bisect
for i in range(int(input())):
	n = int(input())
	A = INPUT()
	ans = []
	for i in range(n):
		if i == 0 or i == n - 1 or (A[i - 1] < A[i]) != (A[i] < A[i + 1]):
			ans.append(A[i])
	print(len(ans))
	print(*ans)
	print()


def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		p = list(map(int, input().split()))
		l = []
		l.append(p[0])
		l.append(p[1])
		for i in range(2, n):
			if p[i] > l[-1]:
				if l[-1] > l[-2]:
					l.pop()
				l.append(p[i])
			else:
				if l[-1] < l[-2]:
					l.pop()
				l.append(p[i])
		print(len(l))
		print(*l)
main()


import collections

def sfinder(a, b):
	if b - a > 0:
		return 1
	if b - a < 0:
		return -1
	else:
		return 0
tests = int(input())
for _ in range(tests):
	n = int(input())
	arr = [int(a) for a in input().strip().split(' ')]
	slope = 0
	subseq = []
	if arr[1] - arr[0] > 0:
		slope = 1
		subseq.append(arr[0])
	elif arr[1] - arr[0] < 0:
		slope = -1
		subseq.append(arr[0])
	for i in range(2, n):
		if sfinder(arr[i - 1], arr[i]) != slope:
			subseq.append(arr[i - 1])
		slope = sfinder(arr[i - 1], arr[i])
	if slope != 0:
		subseq.append(arr[-1])
	print(len(subseq))
	[print(a, end=' ') for a in subseq]
	print()


import math
from collections import defaultdict
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if n == 2:
		print(2)
		print(*a)
	else:
		ans = []
		for i in range(n):
			if i == 0:
				ans.append(a[0])
			elif i == n - 1:
				ans.append(a[n - 1])
			elif a[i - 1] > a[i] and a[i] > a[i + 1] or (a[i] > a[i - 1] and a[i] < a[i + 1]):
				continue
			else:
				ans.append(a[i])
		print(len(ans))
		print(*ans)


t = int(input())
for u in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = []
	flag = -1
	for i in range(1, n):
		if a[i] > a[i - 1]:
			if flag != 0:
				ans.append(a[i - 1])
				flag = 0
			else:
				flag = 0
		elif flag != 1:
			ans.append(a[i - 1])
			flag = 1
		else:
			flag = 1
	ans.append(a[-1])
	print(len(ans))
	print(*ans)


for t in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	x = [0] * (n - 1)
	s = [p[0]]
	for i in range(n - 1):
		x[i] = p[i] - p[i + 1]
	i = 0
	j = 0
	while i < n - 1:
		while j < n - 1 and x[i] * x[j] > 0:
			j += 1
		i = j
		if i != n - 1:
			s.append(p[i])
	s.append(p[n - 1])
	print(len(s))
	print(*s)


import sys, random, math
from bisect import bisect_left, bisect_right
input = sys.stdin.readline

def main():
	inf = 10 ** 20
	t = int(input())
	for _ in range(1, t + 1):
		n = int(input())
		p = [int(x) for x in input().split()]
		nd = [0]
		for i in range(1, n - 1):
			if p[i] - p[i - 1] > 0 and p[i] - p[i + 1] > 0:
				nd.append(i)
			if p[i] - p[i - 1] < 0 and p[i] - p[i + 1] < 0:
				nd.append(i)
		nd.append(n - 1)
		print(len(nd))
		for x in nd:
			print(p[x], end=' ')
		print()
main()


T = int(input())
while T != 0:
	T -= 1
	n = int(input())
	p = list(map(int, input().split()))
	ans = []
	l = 0
	r = 0
	ans.append(p[0])
	while l < n:
		if l == n - 1:
			break
		else:
			r = l + 1
			while r + 1 < n and (p[r + 1] > p[r]) == (p[l + 1] > p[l]):
				r += 1
			ans.append(p[r])
			l = r
	print(len(ans))
	print(' '.join(map(str, ans)))


t = int(input())
for i in range(t):
	n = int(input())
	num1 = list(map(int, input().split()))
	lis = []
	s = 0
	lis.append(num1[0])
	if num1[1] > num1[0]:
		s = 1
	elif num1[1] < num1[0]:
		s = -1
	for j in range(1, n - 1):
		if s == 1:
			if num1[j + 1] > num1[j]:
				s = 1
			elif num1[j] > num1[j + 1]:
				lis.append(num1[j])
				s = -1
		elif s == -1:
			if num1[j + 1] > num1[j]:
				lis.append(num1[j])
				s = 1
			elif num1[j] > num1[j + 1]:
				s = -1
	lis.append(num1[-1])
	print(len(lis))
	print(' '.join((str(x) for x in lis)))


t = int(input())
for i in range(t):
	ns = int(input())
	nums = list(map(int, input().rstrip().split()))
	i = 0
	res = []
	flag = 0 if nums[1] < nums[0] else 1
	for j in range(1, len(nums)):
		if nums[j - 1] > nums[j] and flag == 1:
			res.append(nums[i])
			i = j - 1
			flag = 0
		if nums[j - 1] < nums[j] and flag == 0:
			res.append(nums[i])
			i = j - 1
			flag = 1
		if j == len(nums) - 1:
			res.append(nums[i])
			res.append(nums[j])
	print(len(res))
	print(' '.join(map(str, res)))


test = int(input())
for t in range(test):
	n = int(input())
	p = list(map(int, input().split()))
	arr = [p[0]]
	for i in range(1, n - 1):
		if p[i] > p[i - 1] and p[i] >= p[i + 1]:
			arr.append(p[i])
		elif p[i] <= p[i + 1] and p[i] < p[i - 1]:
			arr.append(p[i])
	arr.append(p[n - 1])
	print(len(arr))
	for i in range(0, len(arr)):
		print(arr[i], end=' ')
	print('')


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	x = a[0]
	b = [x]
	if a[1] > x:
		t = 1
	else:
		t = 0
	i = 1
	while i < n:
		if t == 1:
			if a[i] > x and a[i] > a[i - 1]:
				i += 1
			else:
				b += [a[i - 1]]
				x = a[i - 1]
				t = 0
		elif a[i] < x and a[i] < a[i - 1]:
			i += 1
		else:
			b += [a[i - 1]]
			x = a[i - 1]
			t = 1
	else:
		b += [a[-1]]
	print(len(b))
	print(*b)


def test(jj, a2, b):
	n = len(b)
	for j in jj:
		b2 = b[n - 1 - j]
		if a2 == b2:
			return True
	return False

def main():
	n = int(input())
	p = list(map(int, input().split(' ')))
	o = [p[0]]
	for i in range(1, n - 1):
		if p[i - 1] <= p[i] <= p[i + 1]:
			continue
		if p[i - 1] >= p[i] >= p[i + 1]:
			continue
		o.append(p[i])
	o.append(p[-1])
	print(len(o))
	print(*o, sep=' ')
for t in range(int(input())):
	main()


for _ in range(int(input())):
	(n, perm) = (int(input()), list(map(int, input().split())))
	i = 1
	while i < n - 1:
		if perm[i - 1] < perm[i] < perm[i + 1]:
			perm.pop(i)
			n -= 1
		elif perm[i - 1] > perm[i] > perm[i + 1]:
			perm.pop(i)
			n -= 1
		else:
			i += 1
	print(n)
	print(' '.join(map(str, perm)))


def tostr(A):
	return [*map(str, A)]

def toint(A):
	return [*map(int, A)]

def solve(A):
	if len(A) <= 2:
		return A
	(i, j, k) = (0, 1, 2)
	ret = []
	while k < len(A):
		if (A[i] - A[j]) * (A[k] - A[j]) > 0:
			ret.append(A[i])
			(i, j, k) = (j, k, k + 1)
		else:
			(i, j, k) = (i, k, k + 1)
	ret.append(A[i])
	ret.append(A[j])
	return ret
from os import sys
ncases = int(sys.stdin.readline().strip())
for _ in range(ncases):
	n = sys.stdin.readline()
	A = sys.stdin.readline().split()
	ret = solve(toint(A))
	print(len(ret))
	print(' '.join(tostr(ret)))


from sys import stdin
A = int(stdin.readline())
for t in range(0, A):
	B = int(stdin.readline())
	C = stdin.readline().split()
	temp1 = int(C[0])
	temp2 = int(C[0])
	ans = 1
	ANS = list()
	ANS.append(int(C[0]))
	hint = temp2 - temp1
	for u in range(1, B):
		temp1 = temp2
		temp2 = int(C[u])
		if temp1 == temp2:
			continue
		elif hint == 0:
			hint += temp2 - temp1
		elif hint > 0:
			if temp2 > temp1:
				hint += temp2 - temp1
			if temp1 > temp2:
				ans += 1
				ANS.append(temp1)
				hint = temp2 - temp1
		elif hint < 0:
			if temp1 > temp2:
				hint += temp2 - temp1
			if temp1 < temp2:
				ANS.append(temp1)
				ans += 1
				hint = temp2 - temp1
	if abs(hint) > 0:
		print(ans + 1)
		ANS.append(int(C[len(C) - 1]))
		print(' '.join(map(str, ANS)))
	elif ans == 1:
		print(2)
		print([C[0], C[len(C) - 1]])
	else:
		print(ans)
		print(' '.join(map(str, ANS)))


import math as ma
import sys
input = sys.stdin.readline
t = int(input())
for i in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	a = []
	for i in range(n - 1):
		a.append(p[i + 1] - p[i])
	e = [p[0]]
	for i in range(n - 2):
		if a[i] > 0 and a[i + 1] < 0:
			e.append(p[i + 1])
		if a[i] < 0 and a[i + 1] > 0:
			e.append(p[i + 1])
	if e[-1] != p[-1]:
		e.append(p[-1])
	print(len(e))
	print(*e)


tc = int(input())
while tc > 0:
	n = int(input())
	p = list(map(int, input().split()))
	ans = [str(p[0])]
	delta = p[1] - p[0]
	for i in range(1, n - 1):
		if (p[i + 1] - p[i]) * delta < 0:
			ans.append(str(p[i]))
			delta = p[i + 1] - p[i]
	ans.append(str(p[n - 1]))
	print(len(ans))
	print(' '.join(ans))
	tc -= 1


from collections import deque
for _ in range(int(input())):
	n = int(input())
	mark = {}
	a = list(map(int, input().split()))
	st = [0]
	for i in range(1, n - 1):
		j = st[-1]
		x = abs(a[i] - a[j]) + abs(a[i] - a[i + 1])
		y = abs(a[j] - a[i + 1])
		if y >= x:
			a[i] = 0
		else:
			st.append(i)
	Ans = []
	for i in range(n):
		if a[i] != 0:
			Ans.append(a[i])
	print(len(Ans))
	print(*Ans)


t = int(input())
for i in range(t):
	f = lambda : map(int, input().split(' '))
	n = int(input())
	p = list(f())
	ans = [p[0]]
	for i in range(1, n - 1):
		if (p[i - 1] < p[i]) != (p[i] < p[i + 1]):
			ans.append(p[i])
	ans.append(p[-1])
	print(len(ans))
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	p = [int(__) for __ in input().split()]
	for i in range(1, n - 1):
		if p[i - 1] < p[i] < p[i + 1]:
			p[i] = 0
	for i in range(1, n - 1):
		if p[i - 1] > p[i] > p[i + 1] and p[i + 1] != 0:
			p[i] = n + 1
	ans = 0
	for i in p:
		if i != 0 and i != n + 1:
			ans += 1
	print(ans)
	for i in p:
		if i != 0 and i != n + 1:
			print(i, end=' ')
	print('')


import sys
from collections import defaultdict as dd
from queue import Queue
import math
import itertools
try:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
except:
	pass
input = lambda : sys.stdin.buffer.readline().rstrip()
for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	q = [a[0]]
	for i in range(1, n - 1):
		if a[i] > a[i - 1] and a[i] > a[i + 1]:
			q.append(a[i])
		if a[i] < a[i - 1] and a[i] < a[i + 1]:
			q.append(a[i])
	if a[n - 1] != a[n - 2]:
		q.append(a[n - 1])
	print(len(q))
	print(*q)


for testcase in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	newarr = [arr[0]]
	increasing = None
	prev = arr[0]
	for i in arr[1:]:
		if i == prev:
			continue
		if increasing is None:
			if i > prev:
				increasing = True
			elif i < prev:
				increasing = False
			newarr.append(i)
			prev = i
			continue
		if increasing:
			if i > prev:
				newarr.pop()
				newarr.append(i)
			elif i < prev:
				increasing = False
				newarr.append(i)
		if not increasing:
			if i > prev:
				newarr.append(i)
				increasing = True
			elif i < prev:
				newarr.pop()
				newarr.append(i)
		prev = i
	print(len(newarr))
	print(*newarr)


t = int(input())
for _ in range(t):
	n = int(input())
	l = list(map(int, input().split()))
	a = [l[0]]
	for i in range(1, n):
		try:
			if (l[i] - l[i - 1]) * (l[i] - l[i + 1]) > 0:
				a.append(l[i])
		except:
			if l[i] != a[-1]:
				a.append(l[i])
	print(len(a))
	for i in a:
		print(i, end=' ')
	print()


from sys import stdin, stdout
import heapq as hq
from collections import defaultdict
t = int(input())
for tc in range(t):
	n = int(stdin.readline())
	ar = list(map(int, stdin.readline().split()))
	removed = 0
	last = ar[0]
	i = 1
	while i < n - 1:
		if abs(last - ar[i]) + abs(ar[i] - ar[i + 1]) <= abs(last - ar[i + 1]):
			ar[i] = -1
			removed += 1
		else:
			last = ar[i]
		i += 1
	stdout.write(str(n - removed) + '\n')
	for val in ar:
		if val > -1:
			stdout.write(str(val) + ' ')
	stdout.write('\n')


from sys import stdin, stdout
for t in range(int(stdin.readline())):
	n = int(stdin.readline())
	a = list(map(int, stdin.readline().strip().split()))
	b = [a[0], a[1]]
	for i in range(2, n):
		if abs(b[-1] - a[i]) + abs(b[-2] - b[-1]) <= abs(b[-2] - a[i]):
			b.pop()
			b.append(a[i])
		else:
			b.append(a[i])
	stdout.write(str(len(b)) + '\n')
	print(*b)


import sys

def input():
	return sys.stdin.readline().rstrip()

def input_split():
	return [int(i) for i in input().split()]
testCases = int(input())
answers = []
for _ in range(testCases):
	n = int(input())
	perm = input_split()
	ans = [perm[0]]
	for i in range(1, n - 1):
		if perm[i] > perm[i - 1] and perm[i] > perm[i + 1]:
			ans.append(perm[i])
		elif perm[i] < perm[i - 1] and perm[i] < perm[i + 1]:
			ans.append(perm[i])
		else:
			pass
	ans.append(perm[-1])
	answers.append(ans)
for ans in answers:
	print(len(ans))
	print(*ans, sep=' ')


def parseint():
	ln = input().split()
	for i in range(len(ln)):
		ln[i] = int(ln[i])
	return ln

def solve(p):
	ret = [p[0]]
	for i in range(1, len(p) - 1):
		if p[i - 1] < p[i] < p[i + 1] or p[i - 1] > p[i] > p[i + 1]:
			continue
		else:
			ret.append(p[i])
	ret.append(p[-1])
	print(len(ret))
	print(' '.join((str(x) for x in ret)))
t = int(input())
for i in range(t):
	n = int(input())
	p = parseint()
	solve(p)


def f(al):
	sl = []
	for i in range(1, len(al)):
		sl.append(al[i] - al[i - 1])
	ans = [al[0]]
	i = 0
	prev = 0
	flag = False
	while i < len(sl):
		if sl[i] > 0 and sl[prev] < 0 or (sl[i] < 0 and sl[prev] > 0):
			if i == len(al) - 1:
				flag = True
			ans.append(al[i])
			prev = i
		i = i + 1
	if not flag:
		ans.append(al[-1])
	return ans
for tc in range(int(input())):
	_ = input()
	al = list(map(int, input().split()))
	temp = f(al)
	print(len(temp))
	print(*temp)


test = int(input())
test_arr = []
for _ in range(test):
	n = int(input())
	arr = list(map(int, input().split()))
	temp = []
	compare = arr[0]
	temp.append(compare)
	flag = 0 if compare < arr[1] else 1
	for i in range(1, n):
		if arr[i] > compare:
			if flag == 0:
				compare = arr[i]
			else:
				temp.append(compare)
				compare = arr[i]
				flag = 0
		elif flag == 1:
			compare = arr[i]
		else:
			temp.append(compare)
			compare = arr[i]
			flag = 1
	temp.append(arr[i])
	test_arr.append(temp)
for t in test_arr:
	print(len(t))
	for i in t:
		print(i, end=' ')
	print('')


T = int(input())
for _ in range(T):
	n = int(input())
	l = list(map(int, input().split()))
	ans = [l[0]]
	small = 0
	big = 0
	flags = 0
	flagb = 0
	for i in range(1, n):
		if l[i] < l[i - 1]:
			if flagb == 1:
				ans.append(big)
				flagb = 0
			small = l[i]
			flags = 1
		else:
			if flags == 1:
				ans.append(small)
				flags = 0
			big = l[i]
			flagb = 1
	ans.append(l[n - 1])
	print(len(ans))
	print(*ans)


for t in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	nlist = []
	i = 0
	nlist.append(arr[0])
	while i < n - 2:
		if arr[i] > arr[i + 1] and arr[i + 1] < arr[i + 2]:
			nlist.append(arr[i + 1])
			i += 1
		elif arr[i] < arr[i + 1] and arr[i + 1] > arr[i + 2]:
			nlist.append(arr[i + 1])
			i += 1
		else:
			del arr[i + 1]
			n -= 1
	if nlist[-1] != arr[-1]:
		nlist.append(arr[-1])
	print(len(nlist))
	print(*nlist)


import sys
from bisect import bisect_left, bisect_right
INF = 1 << 60
t = int(input())
for i in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [p[0]]
	for i in range(2, n):
		gap1 = p[i - 1] - p[i - 2]
		gap2 = p[i] - p[i - 1]
		if gap1 > 0 and gap2 < 0:
			ans.append(p[i - 1])
		elif gap1 < 0 and gap2 > 0:
			ans.append(p[i - 1])
	ans.append(p[-1])
	print(len(ans))
	print(*ans)


for x in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	i = 0
	l1 = []
	l1.append(l[0])
	count = 1
	ma = l[0]
	mi = l[0]
	if l[1] > l[0]:
		i = 1
	for x in range(1, n):
		if i == 0:
			if l[x] < mi:
				mi = l[x]
			else:
				l1.append(mi)
				count += 1
				ma = l[x]
				mi = l[x]
				i = 1
		elif l[x] > ma:
			ma = l[x]
		else:
			l1.append(ma)
			count += 1
			ma = l[x]
			mi = l[x]
			i = 0
	if i == 0:
		l1.append(mi)
		count += 1
	else:
		l1.append(ma)
		count += 1
	print(count)
	for x in l1:
		print(x, end=' ')
	print()


import sys
input = sys.stdin.buffer.readline
Q = int(input())
Query = []
for _ in range(Q):
	N = int(input())
	A = list(map(int, input().split()))
	Query.append((N, A))
for (N, A) in Query:
	B = [A[0]]
	if A[1] > A[0]:
		up = True
		B.append(A[1])
	elif A[1] < A[0]:
		up = False
		B.append(A[1])
	for i in range(2, N):
		a = A[i]
		if B[-1] < a:
			if up:
				B.pop()
				B.append(a)
			else:
				B.append(a)
			up = True
		else:
			if not up:
				B.pop()
			B.append(a)
			up = False
	print(len(B))
	print(*B)


def solve(n, p):
	m = [True] * n
	n_p = [p[0]]
	for i in range(1, n):
		if p[i] != p[i - 1]:
			n_p.append(p[i])
	p = n_p
	n = len(p)
	m = [True] * n
	for i in range(1, n - 1):
		if p[i - 1] < p[i] and p[i] < p[i + 1]:
			m[i] = False
		if p[i - 1] > p[i] and p[i] > p[i + 1]:
			m[i] = False
	print(m.count(True))
	for i in range(n):
		if m[i]:
			print(p[i], end=' ')
	print()
t = int(input())
for i in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	solve(n, p)


t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	i = 1
	ans = [p[0]]
	while i < n - 1:
		if not (p[i - 1] < p[i] < p[i + 1] or p[i - 1] > p[i] > p[i + 1]):
			ans.append(p[i])
		i += 1
	ans.append(p[-1])
	print(len(ans))
	print(*ans)


production = True
import sys, math

def input(input_format=0, multi=0):
	if multi > 0:
		return [input(input_format) for i in range(multi)]
	else:
		next_line = sys.stdin.readline()
		if input_format >= 10:
			use_list = False
			input_format = int(str(input_format)[-1])
		else:
			use_list = True
		if input_format == 0:
			formatted_input = [next_line]
		elif input_format == 1:
			formatted_input = list(map(int, next_line.split()))
		elif input_format == 2:
			formatted_input = list(map(float, next_line.split()))
		elif input_format == 3:
			formatted_input = next_line.split()
		elif input_format == 4:
			formatted_input = (lambda x: [x[0], list(map(int, x[1:]))])(next_line.split())
		elif input_format == 5:
			formatted_input = (lambda x: [x[0], list(map(float, x[1:]))])(next_line.split())
		else:
			formatted_input = [next_line]
		return formatted_input if use_list else formatted_input[0]

def out(output_line, output_format=0, newline=True):
	formatted_output = ''
	if output_format == 0:
		formatted_output = str(output_line)
	elif output_format == 1:
		formatted_output = ' '.join(map(str, output_line))
	elif output_format == 1:
		formatted_output = '\n'.join(map(str, output_line))
	print(formatted_output, end='\n' if newline else '')

def log(*args):
	if not production:
		print('$$$')
		print(*args)

def solve():
	n = input(1)
	p = input(1)
	a = [p[0]]
	d = -1
	for i in p[1:]:
		if i > a[-1]:
			if d == 0:
				a.pop()
			a.append(i)
			d = 0
		elif i < a[-1]:
			if d == 1:
				a.pop()
			a.append(i)
			d = 1
	if len(a) < 2:
		a.append(p[-1])
	out(len(a))
	out(a, 1)
	return
for i in range(input(11)):
	solve()


t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [p[0]]
	lasti = p[0]
	lastd = p[0]
	a = 0
	if p[1] > p[0]:
		a = 1
	for i in p[1:]:
		if a == 1:
			if i >= lasti:
				lasti = i
			else:
				ans.append(lasti)
				lastd = i
				a = 0
		elif i < lastd:
			lastd = i
		else:
			ans.append(lastd)
			lasti = i
			a = 1
	if ans[-1] != p[-1]:
		ans.append(p[-1])
	print(len(ans))
	for i in ans:
		print(i, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	q = [p[0]]
	for i in range(n - 1):
		if p[i] != p[i + 1]:
			q.append(p[i + 1])
	n = len(q)
	ans = [q[0]]
	for i in range(n - 2):
		if q[i] < q[i + 1] and q[i + 1] > q[i + 2]:
			ans.append(q[i + 1])
		elif q[i] > q[i + 1] and q[i + 1] < q[i + 2]:
			ans.append(q[i + 1])
	ans.append(q[n - 1])
	print(len(ans))
	print(' '.join(map(str, ans)))


t = int(input())
for _ in range(t):
	n = int(input())
	arr = list(map(int, input().split(' ')))
	curr = 'inc'
	l = []
	if len(arr) <= 2:
		print(2)
		print(*arr)
		continue
	if arr[1] < arr[0]:
		curr = 'dec'
	l.append(arr[0])
	for i in range(1, len(arr)):
		if curr == 'inc':
			if arr[i] > arr[i - 1]:
				continue
			else:
				l.append(arr[i - 1])
				curr = 'dec'
		elif arr[i] < arr[i - 1]:
			continue
		else:
			l.append(arr[i - 1])
			curr = 'inc'
	l.append(arr[-1])
	print(len(l))
	print(*l)


t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = []
	ans.append(a[0])
	siz = 1
	for j in range(1, n - 1):
		if (a[j] >= a[j - 1]) & (a[j] <= a[j + 1]) or (a[j] <= a[j - 1]) & (a[j] >= a[j + 1]):
			continue
		else:
			ans.append(a[j])
			siz += 1
	ans.append(a[n - 1])
	siz += 1
	print(siz)
	print(*ans)


for _ in range(int(input())):
	n = int(input())
	data = list(map(int, input().split()))
	result = []
	for i in range(n):
		if (i == 0 or data[i - 1] < data[i]) and (i == n - 1 or data[i] > data[i + 1]):
			result.append((i, data[i]))
		if (i == 0 or data[i - 1] > data[i]) and (i == n - 1 or data[i] < data[i + 1]):
			result.append((i, data[i]))
	print(len(result))
	for i in result:
		print(i[1], end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = [0]
	b = list(map(int, input().split()))
	a = a + b
	c = []
	c.append(a[1])
	for i in range(2, n):
		if a[i] > a[i - 1] and a[i] > a[i + 1] or (a[i] < a[i - 1] and a[i] < a[i + 1]):
			c.append(a[i])
		else:
			continue
	c.append(a[n])
	print(len(c))
	print(*c)


t = int(input().strip())
for _ in range(t):
	n = int(input().strip())
	l = [int(a) for a in input().strip().split()]
	i = 0
	s = []
	ans = 0
	while i < n:
		if i < n - 1:
			if l[i] < l[i + 1]:
				ans += 1
				s.append(l[i])
				i += 1
				while i < n - 1:
					if l[i] <= l[i + 1]:
						i += 1
					else:
						break
				if i == n - 1:
					ans += 1
					s.append(l[i])
					break
			else:
				ans += 1
				s.append(l[i])
				i += 1
				while i < n - 1:
					if l[i] >= l[i + 1]:
						i += 1
					else:
						break
				if i == n - 1:
					ans += 1
					s.append(l[i])
					break
		else:
			ans += 1
			s.append(l[i])
			i += 1
	print(ans)
	print(*s)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split(' ')))
	check = []
	for i in range(1, n):
		check.append(a[i] - a[i - 1])
	ans = []
	ans.append(a[0])
	for i in range(1, n - 1):
		if check[i] > 0 and check[i - 1] > 0:
			pass
		elif check[i] < 0 and check[i - 1] < 0:
			pass
		elif check[i] > 0 and check[i - 1] < 0:
			ans.append(a[i])
		elif check[i] < 0 and check[i - 1] > 0:
			ans.append(a[i])
	ans.append(a[-1])
	print(len(ans))
	for raj in range(len(ans)):
		print(ans[raj], end=' ')
	print()


t = int(input(''))
mat = []
for i in range(t):
	input('')
	mat.append(list(map(int, input().split())))
for i in range(t):
	x = mat[i]
	n = len(x)
	j = 0
	ans = []
	while j < n:
		if j == 0 or j == n - 1:
			ans.append(x[j])
		else:
			maxx = max(x[j - 1], x[j], x[j + 1])
			minn = min(x[j - 1], x[j], x[j + 1])
			if x[j] == maxx or x[j] == minn:
				ans.append(x[j])
		j = j + 1
	print(len(ans))
	print(*ans)


t = int(input())
for i in range(t):
	n = int(input())
	s = input().split()
	for j in range(n):
		s[j] = int(s[j])
	l = []
	for j in range(n - 1):
		if s[j + 1] > s[j]:
			l.append(1)
		else:
			l.append(-1)
	l.append(-1 * l[n - 2])
	p = []
	p.append(s[0])
	for j in range(1, n):
		if l[j] != l[j - 1]:
			p.append(s[j])
	print(len(p))
	for j in range(len(p)):
		print(p[j], end=' ')
	print('')


for i in range(int(input())):
	n = int(input())
	a = [int(i) for i in input().split()][:n]
	f = 2
	l = [a[0]]
	x = a[0]
	for j in range(1, len(a) - 1):
		if a[j] > a[j - 1] and a[j] > a[j + 1]:
			l.append(a[j])
			f += 1
		if a[j] < a[j - 1] and a[j] < a[j + 1]:
			l.append(a[j])
			f += 1
	l.append(a[-1])
	print(f)
	print(*l)


for _ in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	if l[0] > l[1]:
		x = 1
	else:
		x = 0
	ans = []
	ans.append(l[0])
	for i in range(1, n):
		if x:
			if l[i - 1] < l[i]:
				ans.append(l[i - 1])
				x = 0
		elif l[i - 1] > l[i]:
			ans.append(l[i - 1])
			x = 1
	if ans[-1] != l[n - 1]:
		ans.append(l[n - 1])
	print(len(ans))
	print(*ans)


l = lambda : map(int, input().split())
t = lambda : int(input())
ss = lambda : input()
from math import log10, log2, ceil, factorial as f
for _ in range(t()):
	n = t()
	s = list(l())
	i = 1
	j = 0
	k = 2
	v = [1] * n
	while i < n - 1:
		if s[j] < s[i] < s[k] or s[j] > s[i] > s[k]:
			v[i] = 0
			i += 1
			k += 1
			j += 1
		else:
			i += 1
			j += 1
			k += 1
	p = []
	for i in range(n):
		if v[i]:
			p.append(s[i])
	print(len(p))
	print(*p)


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	ans = [a[0]]
	bl = None
	for i in range(1, n - 1):
		if a[i - 1] > a[i] and a[i] < a[i + 1] or (a[i - 1] < a[i] and a[i] > a[i + 1]):
			ans.append(a[i])
	ans.append(a[-1])
	print(len(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	isIncreasing = False
	isDecreasing = False
	subSequence = [p[0]]
	for i in range(1, len(p)):
		if p[i] == p[i - 1]:
			continue
		if isIncreasing:
			if p[i] > p[i - 1]:
				continue
			else:
				subSequence.append(p[i - 1])
				isIncreasing = False
				isDecreasing = True
				continue
		elif isDecreasing:
			if p[i] < p[i - 1]:
				continue
			else:
				subSequence.append(p[i - 1])
				isIncreasing = True
				isDecreasing = False
				continue
		elif p[i] > p[i - 1]:
			isIncreasing = True
			continue
		else:
			isDecreasing = True
			continue
	subSequence.append(p[len(p) - 1])
	print(len(subSequence))
	output = [str(i) for i in subSequence]
	print(' '.join(output))


t = int(input())
ans = []
ans2 = []
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	inc = 0
	dec = 0
	num = 0
	while True:
		if a[num] != a[num + 1]:
			if a[num] > a[num + 1]:
				dec = 1
				break
			else:
				inc = 1
				break
		num += 1
	br = [a[0]]
	for j in range(n - 1):
		if a[j] == a[j + 1]:
			continue
		else:
			if inc and a[j] > a[j + 1]:
				inc = 0
				dec = 1
				br.append(a[j])
				continue
			if dec and a[j] < a[j + 1]:
				dec = 0
				inc = 1
				br.append(a[j])
	br.append(a[n - 1])
	ans.append(len(br))
	ans2.append(br)
for jj in range(t):
	print(ans[jj])
	for m in ans2[jj]:
		print(m, end=' ')


t = int(input())
ans = [0] * t
for _ in range(t):
	n = int(input())
	s = list(map(int, input().split()))
	ans = [s[0]]
	k = 0
	swt = 0
	for i in range(1, n):
		temp = s[i] - s[i - 1]
		if swt == 0:
			if temp < 0:
				swt = -1
			elif temp > 0:
				swt = 1
		if swt == 1:
			if temp < 0:
				ans.append(s[i - 1])
				swt = -1
		if swt == -1:
			if temp > 0:
				ans.append(s[i - 1])
				swt = 1
	ans.append(s[-1])
	print(len(ans))
	print(' '.join(map(str, ans)))


testCases = int(input())
while testCases > 0:
	size = int(input())
	permutation = list(map(int, input().split()))
	subsequence = [permutation[0]]
	if permutation[0] > permutation[1]:
		operation = 'bigger'
	else:
		operation = 'smaller'
	for i in range(1, size - 1):
		if operation == 'bigger' and permutation[i] > permutation[i + 1] or (operation == 'smaller' and permutation[i] < permutation[i + 1]):
			continue
		subsequence.append(permutation[i])
		if operation == 'bigger':
			operation = 'smaller'
		else:
			operation = 'bigger'
	subsequence.append(permutation[-1])
	print(len(subsequence))
	for i in range(len(subsequence)):
		if i == len(subsequence) - 1:
			print(str(subsequence[i]))
		else:
			print(str(subsequence[i]) + ' ', end='')
	testCases -= 1


import math
import heapq, bisect
import sys
from collections import deque
from fractions import Fraction
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] <= key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] > k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
for ik in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	ans = [l[0]]
	prev = l[1] - l[0]
	for i in range(2, n):
		e = l[i] - l[i - 1]
		if Fraction(e, prev) > 0:
			continue
		else:
			ans.append(l[i - 1])
		prev = e
	if ans[-1] != l[-1]:
		ans.append(l[-1])
	print(len(ans))
	print(*ans, sep=' ')


for _ in range(int(input())):
	am = int(input())
	arr = list(map(int, input().split()))
	need = [arr[0]]
	for i in range(1, am - 1):
		if not (arr[i - 1] > arr[i] and arr[i] > arr[i + 1] or (arr[i - 1] < arr[i] and arr[i] < arr[i + 1])):
			need.append(arr[i])
	need.append(arr[am - 1])
	print(len(need))
	print(*need)


from collections import defaultdict
import sys, math
f = None
try:
	f = open('q1.input', 'r')
except IOError:
	f = sys.stdin
if 'xrange' in dir(__builtins__):
	range = xrange
sys.setrecursionlimit(10 ** 2)

def print_case_iterable(case_num, iterable):
	print('Case #{}: {}'.format(case_num, ' '.join(map(str, iterable))))

def print_case_number(case_num, iterable):
	print('Case #{}: {}'.format(case_num, iterable))

def print_iterable(A):
	print(' '.join(A))

def read_int():
	return int(f.readline().strip())

def read_int_array():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def read_string():
	return list(f.readline().strip())

def ri():
	return int(f.readline().strip())

def ria():
	return [int(x) for x in f.readline().strip().split(' ')]

def rns():
	a = [x for x in f.readline().split(' ')]
	return (int(a[0]), a[1].strip())

def rs():
	return list(f.readline().strip())

def bi(x):
	return bin(x)[2:]
from collections import deque
import math
NUMBER = 998244353

def factorial(n):
	M = NUMBER
	f = 1
	for i in range(1, n + 1):
		f = f * i % M
	return f

def mult(a, b):
	return a * b % NUMBER

def minus(a, b):
	return (a - b) % NUMBER

def plus(a, b):
	return (a + b) % NUMBER

def egcd(a, b):
	if a == 0:
		return (b, 0, 1)
	else:
		(g, y, x) = egcd(b % a, a)
		return (g, x - b // a * y, y)

def modinv(a):
	m = NUMBER
	(g, x, y) = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return x % m

def choose(n, k):
	if n < k:
		assert false
	return mult(factorial(n), modinv(mult(factorial(k), factorial(n - k))))
from collections import deque, defaultdict
import heapq

def solution(a, n):
	sol = [a[0]]
	if a[1] > a[0]:
		up = True
	else:
		up = False
	sol.append(a[1])
	for i in range(1, n):
		if a[i] > a[i - 1]:
			if up:
				sol[-1] = a[i]
			else:
				sol.append(a[i])
				up = True
		elif not up:
			sol[-1] = a[i]
		else:
			sol.append(a[i])
			up = False
	return str(len(sol)) + '\n' + ' '.join(map(str, sol))

def main():
	T = ri()
	for i in range(T):
		n = ri()
		a = ria()
		x = solution(a, n)
		if 'xrange' not in dir(__builtins__):
			print(x)
		else:
			(print >> output, str(x))
	if 'xrange' in dir(__builtins__):
		print(output.getvalue())
		output.close()
if 'xrange' in dir(__builtins__):
	import cStringIO
	output = cStringIO.StringIO()
main()


t = int(input())
while t > 0:
	t = t - 1
	n = int(input())
	a = input()
	A = list(map(int, list(a.split())))
	ans = [0] * n
	p = [A[0]]
	for i in range(n - 1):
		if i == 0:
			if A[1] - A[0] > 0:
				ans[i] = 1
			else:
				ans[i] = -1
		else:
			if A[i + 1] - A[i] > 0:
				ans[i] = 1
			else:
				ans[i] = -1
			if ans[i] != ans[i - 1]:
				p.append(A[i])
	p.append(A[n - 1])
	print(len(p))
	for i in p:
		print(i, end=' ')
	print()


t = int(input())
for _ in range(t):
	n = int(input())
	perm = [int(x) for x in input().split()]
	result = [perm[0]]
	for i in range(1, n - 1):
		(leftVal, rightVal) = (perm[i - 1], perm[i + 1])
		curVal = perm[i]
		curDiff = abs(leftVal - curVal) + abs(rightVal - curVal)
		newDiff = abs(leftVal - rightVal)
		if newDiff < curDiff:
			result.append(curVal)
	result.append(perm[-1])
	print(len(result))
	print(*result)


t = int(input())
for i in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [p[0]]
	t = p[1]
	if p[0] > t:
		current = -1
	else:
		current = 1
	for x in p[2:]:
		if current == 1:
			if t < x:
				t = x
			else:
				ans.append(t)
				t = x
				current = -1
		elif t > x:
			t = x
		else:
			ans.append(t)
			t = x
			current = 1
	ans.append(p[-1])
	print(len(ans))
	print(*ans)


t = int(input())
for i in range(t):
	n = int(input())
	ps = [int(a) for a in input().split()]
	ps.insert(0, 0)
	ps.append(0)
	an = [ps[1]]
	for j in range(2, n):
		if ps[j] > ps[j - 1] and ps[j] > ps[j + 1]:
			an.append(ps[j])
		if ps[j] < ps[j - 1] and ps[j] < ps[j + 1]:
			an.append(ps[j])
	an.append(ps[-2])
	print(len(an))
	for a in an:
		print(a, end=' ')
	print('\n')


t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	if n == 2:
		print(2)
		print(p[0], p[1])
		continue
	ans = list()
	ans.append(p[0])
	for i in range(2, n):
		if p[i] - p[i - 1] > 0 and p[i - 1] - p[i - 2] > 0 or (p[i] - p[i - 1] < 0 and p[i - 1] - p[i - 2] < 0):
			continue
		ans.append(p[i - 1])
	ans.append(p[n - 1])
	print(len(ans))
	for i in range(len(ans)):
		print(ans[i], end=' ')
	print()


def solution(arr):
	ans = []
	slope = []
	for i in range(1, len(arr)):
		val = arr[i] - arr[i - 1]
		if val < 0:
			val = -1
		elif val > 0:
			val = 1
		slope.append(val)
	ans.append(arr[0])
	for i in range(1, len(slope)):
		if slope[i - 1] != slope[i]:
			ans.append(arr[i])
	ans.append(arr[-1])
	return ans
for _ in range(int(input())):
	n = int(input())
	arr = [int(a) for a in input().split()]
	ans = solution(arr)
	print(len(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	a = []
	for i in range(n):
		if i == 0 or i == n - 1:
			a.append(p[i])
		elif p[i] > p[i - 1] and p[i] > p[i + 1]:
			a.append(p[i])
		elif p[i] < p[i - 1] and p[i] < p[i + 1]:
			a.append(p[i])
	print(len(a))
	for i in range(len(a) - 1):
		print(a[i], end=' ')
	print(a[-1])


t = int(input())
for df in range(t):
	B = []
	n = int(input())
	A = list(map(int, input().split()))
	ans = 0
	B.append(A[0])
	for i in range(0, n - 2):
		if A[i] <= A[i + 1] <= A[i + 2] or A[i] >= A[i + 1] >= A[i + 2]:
			continue
		else:
			B.append(A[i + 1])
	B.append(A[n - 1])
	print(len(B))
	print(*B)


import itertools

def brute(arr):
	n = len(arr)
	resultCmp = 0
	result = []
	for k in range(n, 1, -1):
		for combo in itertools.combinations(arr, k):
			subseq = list(combo)
			currCmp = 0
			for i in range(len(subseq) - 1):
				currCmp += abs(subseq[i] - subseq[i + 1])
			if currCmp >= resultCmp:
				resultCmp = currCmp
				result = subseq
	return result

def soln(arr):
	result = [arr[0]]
	currNum = arr[1]
	if arr[1] > arr[0]:
		goingUp = True
	else:
		goingUp = False
	for i in range(2, len(arr) - 1):
		num = arr[i]
		if goingUp:
			if num > currNum:
				currNum = num
			else:
				result.append(currNum)
				currNum = num
				goingUp = False
		elif num < currNum:
			currNum = num
		else:
			result.append(currNum)
			currNum = num
			goingUp = True
	if currNum not in [0, float('inf')]:
		if goingUp and currNum > arr[-1]:
			result.append(currNum)
		elif not goingUp and currNum < arr[-1]:
			result.append(currNum)
	result.append(arr[-1])
	return result

def test():
	arr = [4, 3, 1, 2, 5]
	b = brute(arr)
	f = soln(arr)
	print(b, f)

def randomTest():
	import random
	t = 2 * 10 ** 4
	for i in range(1, t + 1):
		n = random.randint(2, 10 ** 5)
		arr = list(range(1, n + 1))
		random.shuffle(arr)
		print(i)
		f = soln(arr)

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		arr = [int(x) for x in input().split()]
		result = soln(arr)
		print(len(result))
		print(' '.join((str(x) for x in result)))
main()


for _ in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	count = 0
	l = 1
	indexes = set()
	for i in range(1, n - 1):
		if abs(arr[i - l] - arr[i]) + abs(arr[i + 1] - arr[i]) <= abs(arr[i - l] - arr[i + 1]):
			count += 1
			l += 1
			indexes.add(i)
		else:
			l = 1
	print(n - count)
	for i in range(n):
		if i not in indexes:
			print(arr[i], end=' ')
	print()


from sys import stdin, stdout
from collections import deque
input = stdin.readline

def print(x='', end='\n'):
	stdout.write(str(x) + end)

def solve():
	n = int(input())
	l = list(map(int, input().split()))
	ans = [1] * n
	summ = 0
	for i in range(n - 1):
		summ += abs(l[i + 1] - l[i])
	for i in range(1, n - 1):
		(x, y) = (-1, -1)
		csum = summ - abs(l[i + 1] - l[i])
		csum -= abs(l[i - 1] - l[i])
		psum = csum + abs(l[i + 1] - l[i - 1])
		if psum >= summ:
			summ = psum
			ans[i] = 0
	print(ans.count(1))
	for i in range(n):
		if ans[i]:
			print(l[i], end=' ')
	print()
tt = 1
tt = int(input())
for __ in range(tt):
	solve()


t = int(input())
for i in range(t):
	n = int(input())
	list1 = list(map(int, input().split()))
	d = []
	array = []
	if list1[1] > list1[0]:
		asc = 1
		dsc = 0
		l = 0
		r = 1
	elif list1[0] > list1[1]:
		dsc = 1
		asc = 0
		l = 0
		r = 1
	for j in range(1, n):
		if list1[j] > list1[j - 1] and dsc == 1:
			asc = 1
			dsc = 0
			d.append((l, r))
			r = j
			l = j - 1
		elif list1[j] < list1[j - 1] and asc == 1:
			dsc = 1
			asc = 0
			d.append((l, r))
			r = j
			l = j - 1
		if list1[j] > list1[j - 1] and asc == 1:
			r = j
		elif list1[j] < list1[j - 1] and dsc == 1:
			r = j
	d.append((l, r))
	for j in range(len(d)):
		array.append(list1[d[j][0]])
	array.append(list1[d[j][1]])
	print(len(array))
	print(*array)


for _ in range(int(input())):
	n = int(input())
	a = [int(x) for x in input().split()]
	b = []
	b.append(a[0])
	for i in range(1, n - 1):
		l = min(a[i - 1], a[i], a[i + 1])
		k = max(a[i - 1], a[i], a[i + 1])
		if a[i] == l or a[i] == k:
			b.append(a[i])
	b.append(a[-1])
	print(len(b))
	for i in b:
		print(i, end=' ')
	print()


def main():
	for __ in [0] * int(input()):
		N = int(input())
		(*A,) = map(int, input().split())
		B = [A[0]]
		p2 = A[0]
		p1 = A[0]
		for a in A:
			if p2 <= p1 <= a or p2 >= p1 >= a:
				p2 = p1
				p1 = a
				continue
			B.append(p1)
			p2 = p1
			p1 = a
		B.append(p1)
		print(len(B))
		print(*B)
main()


def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		ar = list(map(int, input().split()))
		res = [ar[0]]
		prev = 1
		up = (True, False)[ar[0] > ar[1]]
		for i in range(2, n):
			if ar[i - 1] < ar[i] and (not up):
				up = True
				res.append(ar[i - 1])
			elif ar[i - 1] > ar[i] and up:
				up = False
				res.append(ar[i - 1])
		res.append(ar[n - 1])
		print(len(res))
		for x in res:
			print(x, end=' ')
		print()
main()


t = int(input())
for _ in range(t):
	n = int(input())
	arr = [int(i) for i in input().split()]
	start = 0
	end = start + 1
	diff = abs(arr[start] - arr[end])
	end += 1
	len_a = n
	ans = [arr[0]]
	while end < n:
		if diff + abs(arr[end] - arr[end - 1]) == abs(arr[end] - arr[start]):
			diff += abs(arr[end] - arr[end - 1])
			len_a -= 1
		else:
			start = end - 1
			diff = abs(arr[start] - arr[end])
			ans.append(arr[start])
		end += 1
	ans.append(arr[end - 1])
	print(len_a)
	print(*ans)


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	res = [0]
	start = 0
	s = 0
	for i in range(1, n):
		s += abs(a[i] - a[i - 1])
		if s == abs(a[start] - a[i]):
			continue
		res += [i - 1]
		start = i - 1
		s = abs(a[i] - a[i - 1])
	res += [i]
	print(len(res))
	for x in res:
		print(a[x], end=' ')
	print('')


t = int(input())
for i in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	s = [p[0]]
	i = 1
	s1 = 0
	for i in range(1, len(p) - 1):
		if p[i] > p[i - 1] and p[i] > p[i + 1]:
			s.append(p[i])
		if p[i] < p[i - 1] and p[i] < p[i + 1]:
			s.append(p[i])
	s.append(p[n - 1])
	s1 = map(str, s)
	r = ' '.join(s1)
	print(len(s))
	print(r)


def solve(n, ll):
	res = [ll[0]]
	for i in range(1, n - 1):
		if ll[i - 1] < ll[i] > ll[i + 1] or ll[i - 1] > ll[i] < ll[i + 1]:
			res.append(ll[i])
	res.append(ll[-1])
	print(len(res))
	print(*res)
	return
t = int(input())
while t != 0:
	n = int(input())
	ll = list(map(int, input().split()))
	solve(n, ll)
	t -= 1


t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().strip().split()))[:n]
	out = []
	flag = 1
	if arr[0] > arr[1]:
		flag = 0
	out.append(arr[0])
	for i in range(2, n):
		if arr[i] < arr[i - 1] and flag == 1:
			out.append(arr[i - 1])
			flag = 0
		if arr[i] > arr[i - 1] and flag == 0:
			out.append(arr[i - 1])
			flag = 1
	out.append(arr[n - 1])
	l = len(out)
	print(l)
	for i in range(l):
		print(out[i], end=' ')
	print(' ')


t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().strip().split()))[:n]
	if a[0] < a[1]:
		last = 1
	else:
		last = 0
	ans = []
	ans.append(a[0])
	for i in range(n - 1):
		if last == 1 and a[i + 1] >= a[i]:
			continue
		elif last == 1 and a[i + 1] < a[i]:
			last = 0
			ans.append(a[i])
		elif last == 0 and a[i + 1] <= a[i]:
			continue
		elif last == 0 and a[i + 1] > a[i]:
			last = 1
			ans.append(a[i])
	ans.append(a[n - 1])
	print(len(ans))
	for num in ans:
		print(num, end=' ')
	print()


T = int(input())
for _ in range(0, T):
	n = int(input())
	P = list(map(int, input().split()))
	P1 = list()
	for i in range(0, n):
		if i == 0 or i == n - 1 or (P[i - 1] < P[i]) != (P[i] < P[i + 1]):
			P1.append(P[i])
	print(len(P1))
	print(' '.join(map(str, P1)))


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	p = [a[0]]
	i = 1
	asc = a[1] > a[0]
	while i < n:
		if a[i] < a[i - 1] and asc or (a[i] > a[i - 1] and (not asc)):
			asc = not asc
			p.append(a[i - 1])
		i += 1
	p.append(a[n - 1])
	print(len(p))
	print(*p)


t = int(input())
for i in range(t):
	n = int(input())
	arr = list(map(int, input().split()))

	def check(arr, n):
		brr = []
		brr.append(arr[0])
		for i in range(1, n - 1):
			if arr[i] > arr[i - 1] and arr[i] > arr[i + 1] or (arr[i] < arr[i - 1] and arr[i] < arr[i + 1]):
				brr.append(arr[i])
		brr.append(arr[-1])
		print(len(brr))
		for i in brr:
			print(i, end=' ')
		print()
		return
	check(arr, n)


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 998244353

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split()]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n')]

def li3():
	return [int(i) for i in input().rstrip('\n')]

def do(l):
	ind = l.index(1)
	l1 = [1]
	par = 1
	last = 1
	while ind >= 0:
		if l[ind] < last and par or (par == 0 and l[ind] > last):
			l1.append(last)
			par = 1 - par
		last = l[ind]
		ind -= 1
	l1.append(last)
	l1 = l1[::-1]
	ind = l.index(1)
	par = 1
	last = 1
	while ind < len(l):
		if l[ind] < last and par or (par == 0 and l[ind] > last):
			l1.append(last)
			par = 1 - par
		last = l[ind]
		ind += 1
	l1.append(last)
	if l1.count(1) > 1:
		l1.remove(1)
	return l1
for _ in range(val()):
	n = val()
	l = li()
	ans = 0
	l1 = do(l)
	print(len(l1))
	print(*l1)


def solve():
	n = int(input())
	a = [int(x) for x in input().split()]
	temp = []
	temp.append(a[0])
	for j in range(1, n - 1):
		if a[j - 1] < a[j] and a[j] > a[j + 1] or (a[j] < a[j - 1] and a[j] < a[j + 1]):
			temp.append(a[j])
	temp.append(a[n - 1])
	print(len(temp))
	for i in range(len(temp)):
		print(temp[i], end=' ')
t = int(input())
while t:
	solve()
	t -= 1


import sys

def input():
	return sys.stdin.readline().strip()

def iinput():
	return int(input())

def rinput():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1000000000.0) + 7
for _ in range(iinput()):
	n = iinput()
	p = get_list()
	ans = [p[0]]
	for i in range(1, n - 1, 1):
		if p[i] > p[i - 1] and p[i] > p[i + 1] or (p[i] < p[i - 1] and p[i] < p[i + 1]):
			ans.append(p[i])
	ans.append(p[-1])
	print(len(ans))
	print(*ans)


t = int(input())
for f in range(t):
	n = int(input())
	p = input().split()
	for i in range(n):
		p[i] = int(p[i])
	a = [p[0]]
	for i in range(1, n - 1):
		if p[i - 1] < p[i] and p[i] > p[i + 1] or (p[i - 1] > p[i] and p[i] < p[i + 1]):
			a.append(p[i])
	a.append(p[n - 1])
	print(len(a))
	for x in a:
		print(x, end=' ')
	print()


t = int(input())
INF = float('inf')
rr = lambda : input()
rri = lambda : int(input())
rrm = lambda : list(map(int, input().split()))

def solve(N, arr):
	ans = [arr[0]]
	dir = None
	i = 1
	while i < N:
		if dir == None and arr[i] != ans[0]:
			if arr[i] < ans[0]:
				dir = 'dec'
			else:
				dir = 'inc'
		if dir == 'inc':
			if arr[i] >= arr[i - 1]:
				pass
			else:
				dir = 'dec'
				ans.append(arr[i - 1])
		elif arr[i] <= arr[i - 1]:
			pass
		else:
			dir = 'inc'
			ans.append(arr[i - 1])
		i += 1
	if ans[-1] != arr[-1]:
		ans.append(arr[-1])
	print(len(ans))
	print(' '.join(list(map(str, ans))))
for _ in range(t):
	n = rri()
	arr = rrm()
	solve(n, arr)


import sys
input = sys.stdin.readline

def inp():
	return int(input())

def inlist():
	return list(map(int, input().split()))

def instr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())
t = inp()
for l in range(t):
	n = inp()
	p = inlist()
	ans = []
	less = True
	if p[0] > p[1]:
		less = False
	ans.append(p[0])
	for i in range(len(p) - 1):
		if less == True:
			if p[i] > p[i + 1]:
				ans.append(p[i])
				less = False
		elif less == False:
			if p[i] < p[i + 1]:
				ans.append(p[i])
				less = True
	ans.append(p[len(p) - 1])
	print(len(ans))
	for i in range(len(ans)):
		print(ans[i], end=' ')
	print('')


def solve():
	n = int(input())
	arr = [int(v) for v in input().split()]
	(i, j) = (0, 0)
	ans = []
	while i < n:
		j = i + 1
		if j == n:
			ans.append(arr[i])
			break
		elif arr[j] > arr[i]:
			while j < n and arr[j] > arr[j - 1]:
				j += 1
			ans.extend([arr[i]])
			i = j - 1
		else:
			while j < n and arr[j] < arr[j - 1]:
				j += 1
			ans.extend([arr[i]])
			i = j - 1
	print(len(ans))
	print(' '.join((str(v) for v in ans)))
t = int(input())
for _ in range(t):
	solve()


import sys
input = sys.stdin.buffer.readline
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	ans = []
	for val in a:
		if len(ans) < 2:
			ans.append(val)
			continue
		if ans[-1] < val:
			if ans[-2] < ans[-1]:
				ans.pop()
				ans.append(val)
			else:
				ans.append(val)
		elif ans[-1] > val:
			if ans[-2] > ans[-1]:
				ans.pop()
				ans.append(val)
			else:
				ans.append(val)
	print(len(ans))
	print(*ans)


t = int(input())
for q in range(t):
	ans = []
	l = 0
	n = int(input())
	k = 0
	i = 1
	for f in input().split():
		c = int(f)
		if i == 1:
			k += 1
			ans.append(c)
			p = c
		elif i == 2:
			pp = p
			p = c
		else:
			if (pp < p and p < c or (pp > p and p > c)) == False:
				k += 1
				ans.append(p)
			pp = p
			p = c
		i += 1
	ans.append(c)
	k += 1
	print(k)
	for el in ans:
		print(el, end=' ')
	print()


import sys
import heapq

def main():
	t = int(input())
	for _ in range(t):
		n = int(input())
		nums = list(map(int, sys.stdin.readline().split()))
		if n == 2:
			print(2)
			print(nums[0], nums[1])
			continue
		ans = []
		diffFlag = False
		for i in range(n - 1):
			if nums[i + 1] != nums[i]:
				diffFlag = True
				break
		if not diffFlag:
			print(2)
			print(nums[0], nums[1])
			continue
		for pointer in range(2, n):
			if nums[pointer - 2] < nums[pointer - 1] and nums[pointer] < nums[pointer - 1]:
				if pointer - 2 == 0:
					ans.append(nums[pointer - 2])
				ans.append(nums[pointer - 1])
				if pointer == n - 1:
					ans.append(nums[pointer])
			elif nums[pointer - 2] > nums[pointer - 1] and nums[pointer] > nums[pointer - 1]:
				if pointer - 2 == 0:
					ans.append(nums[pointer - 2])
				ans.append(nums[pointer - 1])
				if pointer == n - 1:
					ans.append(nums[pointer])
			elif nums[pointer - 2] > nums[pointer - 1] and nums[pointer] == nums[pointer - 1]:
				if pointer - 2 == 0:
					ans.append(nums[pointer - 2])
				ans.append(nums[pointer - 1])
			elif nums[pointer - 2] < nums[pointer - 1] and nums[pointer] == nums[pointer - 1]:
				if pointer - 2 == 0:
					ans.append(nums[pointer - 2])
				ans.append(nums[pointer - 1])
			elif nums[pointer - 2] == nums[pointer - 1] and nums[pointer] > nums[pointer - 1]:
				ans.append(nums[pointer - 1])
				if pointer == n - 1:
					ans.append(nums[pointer])
			elif nums[pointer - 2] == nums[pointer - 1] and nums[pointer] < nums[pointer - 1]:
				ans.append(nums[pointer - 1])
				if pointer == n - 1:
					ans.append(nums[pointer])
			else:
				if pointer == 2 and nums[0] != nums[1]:
					ans.append(nums[0])
				if pointer == n - 1 and nums[-1] != nums[-2]:
					ans.append(nums[-1])
		print(len(ans))
		for i in ans:
			print(i, end=' ')
		print('')
	return
main()


def ca1(n, lis):
	l1 = 0
	l2 = 0
	for i in range(1, n):
		if l1 == 0:
			if lis[i] >= lis[i - 1]:
				pass
			else:
				nu1.append(lis[i - 1])
				l1 = 1
				l2 = 0
		elif lis[i] <= lis[i - 1]:
			pass
		else:
			nu1.append(lis[i - 1])
			l1 = 0
			l2 = 1
	nu1.append(lis[-1])
	return nu1

def ca2(n, lis):
	l1 = 0
	l2 = 0
	for i in range(1, n):
		if l1 == 0:
			if lis[i] <= lis[i - 1]:
				pass
			else:
				nu2.append(lis[i - 1])
				l1 = 1
				l2 = 0
		elif lis[i] >= lis[i - 1]:
			pass
		else:
			nu2.append(lis[i - 1])
			l1 = 0
			l2 = 1
	nu2.append(lis[-1])
	return nu2
t = int(input())
for tc in range(t):
	n = int(input())
	lis = list(map(int, input().split()))
	nu1 = [lis[0]]
	nu2 = [lis[0]]
	re1 = nu1
	re2 = nu2
	if lis[0] < lis[1]:
		re1 = ca1(n, lis)
	else:
		re2 = ca2(n, lis)
	if len(re1) > len(re2):
		l1 = len(re1)
		print(l1)
		for i in re1:
			print(i, end=' ')
		print()
	else:
		l2 = len(re2)
		print(l2)
		for i in re2:
			print(i, end=' ')
		print()


t = int(input())
for i in range(t):
	n = int(input())
	s = list(map(int, input().split()))
	target = -1
	prev = -1
	if n == 2:
		print(2)
		print(*s)
	else:
		fin_list = list()
		target = s[0]
		prev = s[1]
		for i in range(2, len(s)):
			if target == prev:
				if s[i] == target:
					continue
				else:
					prev = s[i]
			elif target < prev:
				if s[i] >= prev:
					prev = s[i]
				else:
					fin_list.append(target)
					target = prev
					prev = s[i]
			elif s[i] <= prev:
				prev = s[i]
			else:
				fin_list.append(target)
				target = prev
				prev = s[i]
		fin_list.append(target)
		fin_list.append(prev)
		print(len(fin_list))
		print(*fin_list)


def solve(nums):
	increase = None
	res = [nums[0]]
	for i in range(1, len(nums)):
		if nums[i] > nums[i - 1]:
			if increase == False:
				res.append(nums[i - 1])
			increase = True
		else:
			if increase == True:
				res.append(nums[i - 1])
			increase = False
	res.append(nums[-1])
	return res
t = int(input())
for _ in range(t):
	input()
	nums = list(map(int, input().split()))
	res = solve(nums)
	print(len(res))
	print(' '.join([str(x) for x in res]))


def main(num, lst):
	res = [lst[0]]
	for i in range(1, num - 1):
		if lst[i] > lst[i - 1] and lst[i] > lst[i + 1]:
			res.append(lst[i])
		elif lst[i] < lst[i - 1] and lst[i] < lst[i + 1]:
			res.append(lst[i])
	res.append(lst[-1])
	print(len(res))
	return res
for _ in range(int(input())):
	num = int(input())
	lst = list(map(int, input().split()))
	res = main(num, lst)
	for x in res[:-1]:
		print(x, end=' ')
	print(res[-1])


import sys
from bisect import *
from math import floor, sqrt, ceil, factorial as F, gcd, pi, log
from itertools import chain, combinations, permutations, accumulate
from collections import Counter, defaultdict, OrderedDict, deque
from functools import cmp_to_key, reduce
INT_MAX = sys.maxsize
INT_MIN = -sys.maxsize - 1
mod = 1000000007
ch = 'abcdefghijklmnopqrstuvwxyz'
lcm = lambda a, b: a * b // gcd(a, b)
setbit = lambda x: bin(x)[2:].count('1')

def isPick(a, n, x, i, j):
	if i >= 0 and a[i] > x:
		return False
	if j < n and a[j] > x:
		return False
	return True

def isDown(a, n, x, i, j):
	if i >= 0 and a[i] < x:
		return False
	if j < n and a[j] < x:
		return False
	return True

def pick(a, n):
	ans = set()
	for i in range(n):
		if isPick(a, n, a[i], i - 1, i + 1):
			ans.add(a[i])
	for i in range(n):
		if isDown(a, n, a[i], i - 1, i + 1):
			ans.add(a[i])
	return ans

def solve():
	T = int(sys.stdin.readline())
	for _ in range(T):
		n = int(sys.stdin.readline())
		a = list(map(int, sys.stdin.readline().split()))
		res = pick(a, n)
		ans = []
		for i in range(n):
			if a[i] in res:
				ans.append(a[i])
		print(len(ans))
		print(*ans)
try:
	sys.stdin = open('input.txt', 'r')
except:
	pass
solve()


import io
import os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def get_str():
	return input().decode().strip()

def rint():
	return map(int, input().split())

def oint():
	return int(input())
t = oint()
for _ in range(t):
	n = oint()
	p = list(rint())
	ans = [p[0]]
	if p[0] > p[1]:
		slope = -1
	else:
		slope = 1
	for i in range(1, n):
		if p[i - 1] > p[i] and slope == 1:
			ans.append(p[i - 1])
			slope = -1
			continue
		if p[i - 1] < p[i] and slope == -1:
			ans.append(p[i - 1])
			slope = 1
			continue
	if ans[-1] != p[-1]:
		ans.append(p[-1])
	print(len(ans))
	print(*ans)


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

def inputnums():
	return map(int, input().split())

def inputlist():
	return list(map(int, input().split()))

def inputstring():
	return [x for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
t = int(input())
for q in range(t):
	n = inputnum()
	a = inputlist()
	b = [a[0]]
	for i in range(1, n - 1):
		if a[i] > max(a[i - 1], a[i + 1]) or a[i] < min(a[i - 1], a[i + 1]):
			b.append(a[i])
	b.append(a[n - 1])
	print(len(b))
	print(*b)


def solve():
	n = int(input())
	p = [int(x) for x in input().split()]
	s = [p[0]]
	for i in range(1, n):
		if i == n - 1 or sgn(p[i + 1] - p[i]) != sgn(p[i] - p[i - 1]):
			s.append(p[i])
	print(len(s))
	print(*s)

def sgn(x):
	return abs(x) // x
t = int(input())
for test_case in range(t):
	solve()


from collections import defaultdict

def solve(a, n):
	s = [a[0]]
	f = 0
	if a[0] > a[1]:
		f = 1
	for i in range(1, n - 1):
		if f == 1 and a[i] < a[i + 1]:
			s.append(a[i])
			f = 0
		elif f == 0 and a[i] > a[i + 1]:
			s.append(a[i])
			f = 1
	s.append(a[-1])
	return s
t = int(input())
for _ in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	res = solve(a, n)
	print(len(res))
	print(*res)


from sys import stdin

def iinput():
	return int(stdin.readline())

def sinput():
	return input()

def minput():
	return map(int, stdin.readline().split())

def linput():
	return list(map(int, stdin.readline().split()))
t = iinput()
while t:
	t -= 1
	n = iinput()
	a = linput()
	p = [a[0]]
	for i in range(1, n - 1):
		if (a[i] > a[i - 1]) == (a[i] > a[i + 1]):
			p.append(a[i])
	p.append(a[-1])
	print(len(p))
	print(*p)


T = int(input())
while T > 0:
	n = int(input())
	arr = list(map(int, input().split()))
	res = []
	res.append(arr[0])
	for i in range(1, n - 1):
		if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:
			res.append(arr[i])
		elif arr[i] < arr[i - 1] and arr[i] < arr[i + 1]:
			res.append(arr[i])
	res.append(arr[-1])
	k = len(res)
	print(k)
	print(*res)
	T -= 1


import math

def main_function():
	test_cases = range(int(input()))
	for test_case in test_cases:
		n = int(input())
		p = [int(i) for i in input().split(' ')]
		is_included = [True for i in range(len(p))]
		for i in range(2, len(p)):
			if p[i - 2] > p[i - 1] > p[i] or p[i - 2] < p[i - 1] < p[i]:
				is_included[i - 1] = False
		collector = []
		for i in range(len(is_included)):
			if is_included[i]:
				collector.append(p[i])
		counter = 0
		for i in range(1, len(collector)):
			counter += abs(collector[i] - collector[i - 1])
		print(len(collector))
		print(' '.join([str(u) for u in collector]))
main_function()


import bisect
import decimal
from decimal import Decimal
import os
from collections import Counter
import bisect
from collections import defaultdict
import math
import random
import heapq
from math import sqrt
import sys
from functools import reduce, cmp_to_key
from collections import deque
import threading
from itertools import combinations
from io import BytesIO, IOBase
from itertools import accumulate
decimal.getcontext().prec = 46

def primeFactors(n):
	prime = set()
	while n % 2 == 0:
		prime.add(2)
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			prime.add(i)
			n = n // i
	if n > 2:
		prime.add(n)
	return list(prime)

def getFactors(n):
	factors = []
	i = 1
	while i <= math.sqrt(n):
		if n % i == 0:
			if n // i == i:
				factors.append(i)
			else:
				factors.append(i)
				factors.append(n // i)
		i = i + 1
	return factors

def SieveOfEratosthenes(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	num = []
	for p in range(2, n + 1):
		if prime[p]:
			num.append(p)
	return num

def lcm(a, b):
	return a * b // math.gcd(a, b)

def sort_dict(key_value):
	return sorted(key_value.items(), key=lambda kv: (kv[1], kv[0]))

def list_input():
	return list(map(int, input().split()))

def num_input():
	return map(int, input().split())

def string_list():
	return list(input())

def decimalToBinary(n):
	return bin(n).replace('0b', '')

def binaryToDecimal(n):
	return int(n, 2)

def DFS(n, s, adj):
	visited = [False for i in range(n + 1)]
	stack = []
	stack.append(s)
	while len(stack):
		s = stack[-1]
		stack.pop()
		if not visited[s]:
			visited[s] = True
		for node in adj[s]:
			if not visited[node]:
				stack.append(node)

def solve():
	n = int(input())
	arr = list_input()
	j = 1
	ans = [str(arr[0])]
	prev = arr[0]
	while j < n:
		while j < n and arr[j] < prev:
			prev = arr[j]
			j += 1
		if ans[-1] != str(prev):
			ans.append(str(prev))
		while j < n and arr[j] > prev:
			prev = arr[j]
			j += 1
		if ans[-1] != str(prev):
			ans.append(str(prev))
	print(len(ans))
	print(' '.join(ans))
t = int(input())
for _ in range(t):
	solve()


import sys
t = int(sys.stdin.readline())
for _ in range(t):
	n = int(sys.stdin.readline())
	p = [int(i) for i in sys.stdin.readline().split()]
	ans = [0] * n
	ans[0] = str(p[0])
	at = 1
	for i in range(1, n - 1):
		if p[i - 1] < p[i] < p[i + 1] or p[i - 1] > p[i] > p[i + 1]:
			continue
		else:
			ans[at] = str(p[i])
			at += 1
	ans[at] = str(p[-1])
	print(at + 1)
	print(' '.join(ans[:at + 1]))


def getN():
	return int(input())

def getNM():
	return map(int, input().split())

def getList():
	return list(map(int, input().split()))
from collections import defaultdict, deque
from sys import exit
import math
import copy
from bisect import bisect_left, bisect_right
from heapq import *
import sys
INF = 10 ** 17
MOD = 1000000007
from fractions import *

def inverse(f):
	return 1 / f

def make_next(n, nums):
	imos = [0 for i in range(n)]
	for (i, num) in enumerate(nums):
		if num > i:
			imos[0] += 1
		else:
			imos[i - num] += 1
		if i + num + 1 < n:
			imos[i + num + 1] -= 1
	nx = []
	tmp = 0
	for im in imos:
		tmp += im
		nx.append(tmp)
	return nx

def mantan_check(n, nums):
	if sum(nums) == n ** 2:
		return True
	else:
		return False

def knapsack(tree, vx, l):
	dp = [0 for i in range(l + 1)]
	while True:
		dpcp = copy.copy(dp)
		(v, w) = tree[vx - 1]
		for (i, d) in enumerate(dp):
			if w + i < l + 1:
				if dpcp[w + i] < v + d:
					dpcp[w + i] = v + d
		dp = copy.copy(dpcp)
		vx //= 2
		dp = dpcp
		if vx == 0:
			break
	return max(dp)

def solve():
	n = getN()
	nums = getList()
	ans = [nums[0]]
	if n == 2:
		print(n)
		print(*nums)
		return
	prev = nums[1]
	if nums[0] < nums[1]:
		up = True
	else:
		up = False
	for num in nums[2:]:
		if prev < num:
			cup = True
		else:
			cup = False
		if up != cup:
			ans.append(prev)
		up = cup
		prev = num
	ans.append(nums[-1])
	print(len(ans))
	print(*ans)
	return

def main():
	n = getN()
	for _ in range(n):
		solve()
main()


from collections import deque
t = int(input())
for _ in range(t):
	n = int(input())
	s = list(map(int, input().split()))
	li = []
	for i in range(n):
		li.append(0)
	li[0] = s[0]
	li[1] = s[1]
	count = 1
	for i in range(2, n):
		if li[count - 1] > li[count] > s[i]:
			li[count] = s[i]
		elif li[count - 1] < li[count] < s[i]:
			li[count] = s[i]
		else:
			count += 1
			li[count] = s[i]
	ans = 0
	for i in range(0, n):
		if li[i] == 0:
			break
		ans += 1
	print(ans)
	for i in range(ans):
		print(li[i], end=' ')
	print()


for i in range(int(input())):
	n = int(input())
	arr = list(map(int, input().split()))
	ans = []
	l = arr[0]
	if n == 2:
		print(2)
		print(*arr)
	else:
		for i in range(2, n):
			mid = arr[i - 1]
			if l < mid < arr[i] or l > mid > arr[i]:
				pass
			else:
				ans.append(l)
				l = mid
		ans.append(l)
		ans.append(arr[i])
		print(len(ans))
		print(*ans)


import math
import sys
input = sys.stdin.readline
for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	ans = [p[0]]
	k = 1
	if p[0] < p[1]:
		up = True
	else:
		up = False
	for i in range(1, n):
		if p[i - 1] < p[i]:
			f = True
		else:
			f = False
		if up != f:
			ans.append(p[i - 1])
			k += 1
			up = f
	ans.append(p[n - 1])
	k += 1
	print(k)
	print(*ans)


t = int(input())
for you in range(t):
	n = int(input())
	l = input().split()
	li = [int(i) for i in l]
	lfi = []
	for i in range(n):
		if i == 0 or i == n - 1:
			lfi.append(li[i])
		elif li[i] > li[i + 1] and li[i] > li[i - 1]:
			lfi.append(li[i])
		elif li[i] < li[i + 1] and li[i] < li[i - 1]:
			lfi.append(li[i])
	print(len(lfi))
	for i in lfi:
		print(i, end=' ')
	print()


for _ in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	sub = [a[0]]
	prev = a[0]
	inc = 0
	dec = 0
	for i in range(1, n - 1):
		if (a[i] - a[i - 1]) * (a[i + 1] - a[i]) < 0:
			sub.append(a[i])
	sub.append(a[-1])
	print(len(sub))
	print(*sub)


ii = lambda : int(input())
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
for _ in range(ii()):
	n = ii()
	a = il()
	l = 0
	maxa = -100000000
	k = []
	k.append(a[0])
	for i in range(1, n - 1):
		if a[i] < a[i - 1] and a[i] > a[i + 1] or (a[i] > a[i - 1] and a[i] < a[i + 1]):
			continue
		else:
			k.append(a[i])
	k.append(a[n - 1])
	print(len(k))
	print(*k)


T = int(input())
for t in range(T):
	N = int(input())
	P = [int(_) for _ in input().split()]
	up = P[1] > P[0]
	res = [P[0]]
	for i in range(1, N - 1):
		if up and P[i + 1] < P[i]:
			res.append(P[i])
			up = False
		elif not up and P[i + 1] > P[i]:
			res.append(P[i])
			up = True
	if P[N - 1] != P[N - 2]:
		res.append(P[N - 1])
	print(len(res))
	print(' '.join(map(str, res)))


t = int(input())
while t > 0:
	n = int(input())
	a = [int(x) for x in input().split()]
	if a == sorted(a) or a == sorted(a, reverse=True):
		print(2)
		print(str(a[0]) + ' ' + str(a[-1]))
	else:
		c = []
		c.append(a[0])
		x = a[1] - a[0]
		for i in range(2, len(a)):
			y = a[i] - a[i - 1]
			if x ^ y < 0:
				c.append(a[i - 1])
			x = y
			if i == len(a) - 1:
				c.append(a[-1])
		print(len(c))
		print(*c)
	t = t - 1


import sys
import math
import collections

def get_ints():
	return map(int, sys.stdin.readline().strip().split())

def get_list():
	return list(map(int, sys.stdin.readline().strip().split()))

def get_string():
	return sys.stdin.readline().strip()
for t in range(int(input())):
	n = int(input())
	arr = get_list()
	ans = [arr[0]]
	for i in range(1, n - 1):
		if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:
			ans.append(arr[i])
		elif arr[i] < arr[i - 1] and arr[i] < arr[i + 1]:
			ans.append(arr[i])
	ans.append(arr[n - 1])
	print(len(ans))
	print(*ans)


for _ in range(int(input())):
	N = int(input())
	A = list(map(int, input().split()))
	ans = [A[0]]
	for i in range(1, N - 1):
		if A[i - 1] < A[i] and A[i] > A[i + 1]:
			ans.append(A[i])
		if A[i - 1] > A[i] and A[i] < A[i + 1]:
			ans.append(A[i])
	ans.append(A[-1])
	print(len(ans))
	print(*ans)


import os, io
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
t = int(input())
for _ in range(t):
	n = int(input())
	p = list(map(int, input().split()))
	sum1 = 0
	ans1 = []
	ans1.append(p[0])
	increasing = 1
	for i in range(1, n):
		if increasing == 1 and p[i] > ans1[-1]:
			ans1[-1] = p[i]
			continue
		if increasing == 0 and p[i] < ans1[-1]:
			ans1[-1] = p[i]
			continue
		increasing = 1 - increasing
		ans1.append(p[i])
	for i in range(len(ans1) - 1):
		sum1 += abs(ans1[i + 1] - ans1[i])
	sum2 = 0
	ans2 = []
	ans2.append(p[0])
	increasing = 0
	for i in range(1, n):
		if increasing == 1 and p[i] > ans2[-1]:
			ans2[-1] = p[i]
			continue
		if increasing == 0 and p[i] < ans2[-1]:
			ans2[-1] = p[i]
			continue
		increasing = 1 - increasing
		ans2.append(p[i])
	for i in range(len(ans2) - 1):
		sum2 += abs(ans2[i + 1] - ans2[i])
	if sum1 > sum2 or (sum1 == sum2 and len(ans1) < len(ans2)):
		a = []
		for i in range(len(ans1)):
			a.append(str(ans1[i]))
		print(len(ans1))
		print(' '.join(a))
	else:
		a = []
		for i in range(len(ans2)):
			a.append(str(ans2[i]))
		print(len(ans2))
		print(' '.join(a))


for t in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	if a[1] > a[0]:
		flag = 1
	else:
		flag = 0
	arr = [a[0]]
	for i in range(1, n):
		if flag == 1 and a[i] < a[i - 1]:
			arr.append(a[i - 1])
			flag = 0
		elif flag == 0 and a[i] > a[i - 1]:
			arr.append(a[i - 1])
			flag = 1
	arr.append(a[-1])
	print(len(arr))
	print(*arr)


t = int(input())
for case in range(t):
	n = int(input())
	perm = list(map(int, input().split(' ')))
	length = 1
	seq = [perm[0]]
	if perm[0] < perm[1]:
		mode = 'inc'
	else:
		mode = 'dec'
	for i in range(1, n - 1):
		if mode == 'inc' and perm[i] > perm[i + 1]:
			length += 1
			seq.append(perm[i])
			mode = 'dec'
		if mode == 'dec' and perm[i] < perm[i + 1]:
			length += 1
			seq.append(perm[i])
			mode = 'inc'
	length += 1
	seq.append(perm[n - 1])
	print(length)
	print(*seq)


for _ in range(int(input())):
	n = int(input())
	data = [int(x) for x in input().split()]
	ans = [data[0]]
	for q in range(1, n - 1):
		if data[q] > data[q - 1] and data[q] > data[q + 1] or (data[q] < data[q - 1] and data[q] < data[q + 1]):
			ans.append(data[q])
	ans.append(data[-1])
	print(len(ans))
	for q in ans:
		print(q, end=' ')
	print()


import os
import sys, math
from io import BytesIO, IOBase

def main():
	t = int(input())
	for case in range(t):
		n = int(input())
		l = list(map(int, input().split()))
		ans = [l[0]]
		sign = 1
		if l[0] > l[1]:
			sign = -1
		for i in range(1, n):
			if l[i] > l[i - 1]:
				if sign == -1:
					sign = 1
					ans.append(l[i - 1])
				else:
					continue
			elif sign == 1:
				ans.append(l[i - 1])
				sign = -1
			else:
				continue
		if ans[-1] != l[n - 1]:
			ans.append(l[n - 1])
		print(len(ans))
		for c in ans:
			print(c, end=' ')
		print()
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


for I in range(int(input())):
	n = int(input())
	a = list(map(int, input().split()))
	result = [a[0]]
	for i in range(1, n - 1):
		if a[i] > a[i - 1] and a[i] > a[i + 1] or (a[i] < a[i - 1] and a[i] < a[i + 1]):
			result.append(a[i])
	result.append(a[-1])
	print(len(result))
	print(*result)


ll = lambda : list(map(int, input().split()))
s = lambda : input()
v = lambda : map(int, input().split())
ii = lambda : int(input())
m = 1000000007
for _ in range(ii()):
	n = ii()
	a = ll()
	ans = [a[0]]
	for i in range(1, n - 1):
		if a[i - 1] < a[i] and a[i + 1] < a[i]:
			ans.append(a[i])
		elif a[i - 1] > a[i] and a[i + 1] > a[i]:
			ans.append(a[i])
	ans.append(a[-1])
	print(len(ans))
	print(*ans)


import sys

def input():
	return sys.stdin.readline().strip()

def list2d(a, b, c):
	return [[c] * b for i in range(a)]

def list3d(a, b, c, d):
	return [[[d] * c for j in range(b)] for i in range(a)]

def list4d(a, b, c, d, e):
	return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]

def ceil(x, y=1):
	return int(-(-x // y))

def INT():
	return int(input())

def MAP():
	return map(int, input().split())

def LIST(N=None):
	return list(MAP()) if N is None else [INT() for i in range(N)]

def Yes():
	print('Yes')

def No():
	print('No')

def YES():
	print('YES')

def NO():
	print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
for _ in range(INT()):
	N = INT()
	P = LIST()
	if P[0] < P[1]:
		up = True
	else:
		up = False
	used = [1] * N
	for i in range(1, N - 1):
		if P[i] < P[i + 1]:
			if up:
				used[i] = 0
			else:
				up = True
		elif not up:
			used[i] = 0
		else:
			up = False
	ans = []
	for i in range(N):
		if used[i]:
			ans.append(P[i])
	print(len(ans))
	print(*ans)


t = int(input())
for _ in range(t):
	input()
	a = list(map(int, input().split()))
	b = [0] * len(a)
	for i in range(1, len(b)):
		if a[i] > a[i - 1]:
			b[i] = 1
		elif a[i] == a[i - 1]:
			b[i] = 0
		else:
			b[i] = -1
	ans = [str(a[0])]
	b[0] = b[1]
	for i in range(1, len(a) - 1):
		if b[i] == 0:
			continue
		if b[i] != b[i + 1]:
			ans.append(str(a[i]))
	ans.append(str(a[-1]))
	print(len(ans))
	print(' '.join(map(str, ans)))


def solve():
	n = int(input())
	a = list(map(int, input().split()))
	peaks_and_valleys = []
	for i in range(1, n - 1):
		if a[i] > a[i - 1] and a[i] > a[i + 1]:
			peaks_and_valleys.append(a[i])
		if a[i] < a[i - 1] and a[i] < a[i + 1]:
			peaks_and_valleys.append(a[i])
	peaks_and_valleys = [a[0]] + peaks_and_valleys + [a[-1]]
	print(len(peaks_and_valleys))
	print(' '.join(list(map(str, peaks_and_valleys))))

def main():
	t = int(input())
	test_case_number = 1
	while test_case_number <= t:
		solve()
		test_case_number += 1
main()


for _ in range(int(input())):
	n = int(input())
	p = list(map(int, input().split()))
	if n == 2:
		print(2)
		print(p[0], p[1])
	else:
		f = []
		f.append(p[0])
		inc = 0
		dec = 0
		temp = f[0]
		k = 0
		for i in range(1, n):
			if p[i] > temp and inc == 0:
				if dec == 1:
					f.append(temp)
					k += 1
					dec = 0
				inc = 1
				temp = p[i]
			elif p[i] > temp and inc == 1:
				if p[i] > temp:
					temp = p[i]
			elif p[i] < temp and dec == 0:
				if inc == 1:
					f.append(temp)
					k += 1
					inc = 0
				temp = p[i]
				dec = 1
			elif p[i] < temp and dec == 1:
				if p[i] < temp:
					temp = p[i]
		if temp != f[k]:
			f.append(temp)
			k += 1
		print(k + 1)
		print(' '.join((str(a) for a in f)))


import sys
read = lambda : sys.stdin.readline()

def sign(x):
	return 1 if x > 0 else -1
T = int(read())
for T in range(T):
	n = int(read())
	arr = list(map(int, read().split()))
	dif = []
	for i in range(1, len(arr)):
		dif.append(arr[i] - arr[i - 1])
	groups = [1]
	for i in range(1, len(dif)):
		if sign(dif[i]) == sign(dif[i - 1]):
			groups[-1] += 1
		else:
			groups.append(1)
	result = [arr[0]]
	i = 0
	for g in groups:
		i += g
		result.append(arr[i])
	print(len(result))
	for n in result[:-1]:
		print(n, end=' ')
	print(result[-1])


import sys, math

def data():
	return sys.stdin.buffer.readline().strip()

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
INF = float('inf')
mod = 998244353
for t in range(int(data())):
	n = int(data())
	p = mdata()
	ans = [p[0]]
	for i in range(1, n - 1):
		if p[i - 1] < p[i] > p[i + 1] or p[i - 1] > p[i] < p[i + 1]:
			ans.append(p[i])
	ans.append(p[-1])
	out(len(ans))
	outl(ans)


def f(n, p):
	s = []
	for i in range(1, n - 1):
		if (int(p[i - 1]) - int(p[i])) * (int(p[i]) - int(p[i + 1])) >= 0:
			s.append(i)
	x = len(s)
	for i in range(len(s)):
		p.pop(s[x - 1 - i])
	print(len(p))
	for i in p:
		print(i, end=' ')
	print()
for i in range(int(input())):
	n = int(input())
	p = input().split(' ')
	f(n, p)


t = int(input())
for case in range(t):
	n = int(input())
	p = list(input().split())
	prevComp = ' '
	counter = 0
	for i in range(n - 1):
		if int(p[i]) < int(p[i + 1]):
			currComp = 'less'
			if currComp == prevComp:
				p[i] = ''
			else:
				counter = counter + 1
			prevComp = 'less'
		else:
			currComp = 'more'
			if currComp == prevComp:
				p[i] = ''
			else:
				counter = counter + 1
			prevComp = 'more'
	print(counter + 1)
	p = [i for i in p if i != '']
	print(*p)


import sys
input = sys.stdin.readline
import heapq
import copy
import math
import decimal

def inp():
	return int(input())

def inlt():
	return list(map(int, input().split()))

def insr():
	s = input()
	return list(s[:len(s) - 1])

def insr2():
	s = input()
	return s[:len(s) - 1]

def invr():
	return map(int, input().split())

def pr_list(a):
	print(*a, sep=' ')

def main():
	tests = inp()
	mod = 998244353
	limit = 10 ** 18
	ans = 0
	for test in range(tests):
		n = inp()
		p = inlt()
		ans = [p[0]]
		for i in range(1, n - 1):
			if p[i] > p[i - 1] and p[i] > p[i + 1]:
				ans.append(p[i])
			elif p[i] < p[i - 1] and p[i] < p[i + 1]:
				ans.append(p[i])
		ans.append(p[-1])
		print(len(ans))
		pr_list(ans)
main()


def eval(n, L):
	if len(L) == 2:
		print('2')
		print(' '.join(map(str, L)))
	else:
		st = L[0]
		en = L[-1]
		MID = []
		for i in range(1, n - 1):
			if L[i] < L[i - 1] and L[i] < L[i + 1]:
				MID.append(L[i])
			elif L[i] > L[i - 1] and L[i] > L[i + 1]:
				MID.append(L[i])
		seq = [st] + MID + [en]
		print(len(seq))
		print(' '.join(list(map(str, seq))))
for _ in range(int(input())):
	n = int(input())
	L = list(map(int, input().split()))
	eval(n, L)


for tt in range(int(input())):
	n = int(input())
	l = list(map(int, input().split()))
	l2 = [l[0]]
	for i in range(1, n - 1):
		if l[i] > l[i + 1] and l[i] > l[i - 1] or (l[i] < l[i + 1] and l[i] < l[i - 1]):
			l2.append(l[i])
	l2.append(l[-1])
	print(len(l2))
	print(*l2)


T = int(input())
for _ in range(0, T):
	n = int(input())
	s = [int(x) for x in input().split()]
	turn = 0
	lf = s[0]
	rg = s[1]
	L = [s[0]]
	if rg > lf:
		turn = 1
	for i in range(2, len(s)):
		if turn == 1:
			if s[i] > rg:
				rg = s[i]
			else:
				L.append(rg)
				lf = rg
				rg = s[i]
				turn = 0
		elif s[i] < rg:
			rg = s[i]
		else:
			L.append(rg)
			lf = rg
			rg = s[i]
			turn = 1
	L.append(rg)
	print(len(L))
	print(*L)


def calc(n, a):
	sq = []
	sq.append(a[0])
	sq.append(a[1])
	idx = 1
	i = 2
	while i < n:
		if abs(a[i] - sq[idx]) + abs(sq[idx] - sq[idx - 1]) == abs(a[i] - sq[idx - 1]):
			sq[idx] = a[i]
		else:
			sq.append(a[i])
			idx += 1
		i += 1
	print(len(sq))
	print(*sq)
t = int(input())
for i in range(t):
	n = int(input())
	a = list(map(int, input().split()))
	calc(n, a)