#C14632. Longest Consecutive Subsequence

    ID: 44303 Type: Default 1000ms 256MiB

Longest Consecutive Subsequence

Longest Consecutive Subsequence

Given an unsorted list of integers, your task is to compute the longest subsequence of consecutive integers. A consecutive subsequence is defined such that for a sequence \(a_1, a_2, \ldots, a_k\), it holds that \(a_{i+1} = a_i + 1\) for all valid \(i\). The resulting subsequence must be output in ascending order.

Note the following edge cases:

  • If the list is empty, output 0 and an empty sequence.
  • If all elements are the same, the longest consecutive subsequence is that single number.

Input: The first line contains an integer \(n\) denoting the number of elements. The second line contains \(n\) space-separated integers.

Output: On the first line, print the length of the longest consecutive subsequence. On the second line, print the subsequence elements in ascending order separated by spaces. If there is no subsequence, print an empty line for the sequence.

inputFormat

The input begins with an integer \(n\) (\(n \ge 0\)) representing the number of integers. The next line contains \(n\) space-separated integers. For example:

6
100 4 200 1 3 2

outputFormat

The output consists of two lines. The first line is the length of the longest consecutive subsequence. The second line contains the subsequence itself in ascending order, with each number separated by a space. For example:

4
1 2 3 4
## sample
6
100 4 200 1 3 2
4

1 2 3 4

</p>