------
## 最终结论
```python
def find_max_subsequence(t, test_cases):
    results = []
    
    for case in test_cases:
        n, p = case
        subsequence = []
        
        # Always include the first element
        subsequence.append(p[0])
        
        # Iterate through the permutation to find peaks and valleys
        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]):
                subsequence.append(p[i])
        
        # Always include the last element
        subsequence.append(p[-1])
        
        # Remove duplicates if any (in case of consecutive peaks/valleys)
        unique_subsequence = []
        for num in subsequence:
            if not unique_subsequence or unique_subsequence[-1] != num:
                unique_subsequence.append(num)

        results.append((len(unique_subsequence), unique_subsequence))
    
    return results

# Read input data
import sys
input = sys.stdin.read
data = input().split()

t = int(data[0])
index = 1
test_cases = []

for _ in range(t):
    n = int(data[index])
    index += 1
    p = list(map(int, data[index:index + n]))
    index += n
    test_cases.append((n, p))

# Get results
results = find_max_subsequence(t, test_cases)

# Print the results
for length, subseq in results:
    print(length)
    print(' '.join(map(str, subseq)))
```