Sereja loves integer sequences very much. He especially likes stairs.
Sequence a1, a2, ..., a|a| (|a| is the length of the sequence) is stairs if there is such index i (1 ≤ i ≤ |a|), that the following condition is met:
a1 < a2 < ... < ai - 1 < ai > ai + 1 > ... > a|a| - 1 > a|a|.
For example, sequences [1, 2, 3, 2] and [4, 2] are stairs and sequence [3, 1, 2] isn't.
Sereja has m cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table?
Input
The first line contains integer m (1 ≤ m ≤ 105) — the number of Sereja's cards. The second line contains m integers bi (1 ≤ bi ≤ 5000) — the numbers on the Sereja's cards.
Output
In the first line print the number of cards you can put on the table. In the second line print the resulting stairs.
Examples
Input
5
1 2 3 4 5
Output
5
5 4 3 2 1
Input
6
1 1 2 2 3 3
Output
5
1 2 3 2 1
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
We need to interpret problem: Given multiset of numbers (cards). We can choose a subsequence (order can be arranged arbitrarily? Usually when "put some cards on the table in a row", we can arrange them in any order, because we physically place cards. But careful: The problem likely expects we can arrange the cards in any order to form a stair sequence. But typically in such problems (like constructing a "mountain" or "pyramid" from given numbers), we can reorder the cards arbitrarily to form a sequence. However the input is just multiset of numbers, we can order them. So we need to select a subset (maybe all) and arrange them to satisfy the "stairs" condition: increasing then decreasing with a peak, strictly increasing up to peak, and strictly decreasing after peak. It can be just increasing (i= |a|) or just decreasing (i=1)? Actually condition says: there exists index i such that a1 < a2 < ... < a_{i-1} < a_i > a_{i+1} > ... > a_{|a|}. So if i=1, then there is no left side; condition becomes a1 > a2 > ... > a_n, i.e., strictly decreasing. Similarly i=n yields strictly increasing. Both are allowed.
We need maximum length of a stair sequence using the cards (each card used at most once). So it's about constructing a sequence that is first strictly increasing then strictly decreasing, from the given multiset of numbers.
We need to maximize the number of cards used. Usually we can use each card at most once. We can reorder arbitrarily.
We need to output the sequence (any optimal one).
Given constraints: m up to 1e5, numbers up to 5000.
Observations: The sequence is like a "mountain" shape: we need a peak value that appears exactly once, and all numbers to the left are distinct and increasing (strict), and all to the right are distinct and decreasing. However numbers can repeat across left and right? Since we have multiset, we can use same value possibly on both sides? But condition requires strict inequalities: left side strictly increasing, right side strictly decreasing. So if we have duplicate numbers, they cannot be on same side because that would break strictness. But could the same value appear on left and right? Possibly, as long as they are on different sides, but careful: The peak is strictly greater than both neighbors, so left side values must be strictly less than the peak, right side values must be strictly less than the peak. If we have same value on left and right, that would be okay if they are less than peak and the left side's last element is less than peak, right side's first element is less than peak. But the left side's values themselves must be strictly increasing; if we have two equal numbers, they cannot be adjacent or in the same side. But could we put same value on left and right? For example, sequence [1,2,1] uses two 1's. That's allowed because left side is [1,2] increasing, right side is [1] decreasing (2>1). So duplicates across sides are allowed. However, duplicates on same side are not allowed because strict monotonicity would be violated.
Thus, we need to select a multiset of numbers to form an increasing then decreasing sequence, with each number used at most its frequency. So we need to decide a peak value and then for each value less than the peak, we can use up to at most 2 copies (one on left, one on right), but we may also use only one copy if we place it on one side only. Actually we can use at most min(freq,2) for values less than peak, but careful: For the peak value itself, we can only use one copy (since it's the maximum and appears once). For values less than peak, we can use at most two copies: one on left and one on right. However we are not forced to use both; we may use just one if it helps to include more numbers? But we want maximize total length, so we would want to include as many cards as possible. So for each distinct value v less than peak, we should use up to min(freq[v],2) copies, but maybe using one copy might allow longer sequence? Actually using two copies uses two cards, which is more than one, so it's always better to include as many cards as possible. However there is a catch: The sequence must be strictly increasing to the peak and strictly decreasing after. That means the left side must be a strictly increasing sequence of distinct values (each used once). The right side must be a strictly decreasing sequence of distinct values. So left side uses distinct values, each at most once; right side uses distinct values, each at most once. But the same value can appear once on left and once on right. So overall, for each value v (≠ peak), the maximum number we can include is min(freq[v], 2) if we can place one on each side. But we must ensure that the set of values on left and right can be arranged as increasing and decreasing respectively. That is, we can choose any subset of values for left (each with at least one copy) and any subset for right (each with at least one copy), with the condition that all left values are < peak, all right values < peak, and also left side values are distinct and ordered, right side values are distinct. There's no further restriction: we can pick any combination of values for left and right. So the total length is: 1 (peak) + |L| + |R|, where L and R are disjoint sets? They can intersect: same value can be in both L and R if freq >=2. But if we include v in both sides, then that uses two copies, but the sets L and R share value v; that's fine because they are on different sides. However note that the left side is increasing up to peak, and right side is decreasing from peak. If a value appears on both sides, then on left side, the last element before peak must be less than peak; on right side, the first element after peak must be less than peak. That's okay. But the order on right side is decreasing, so the values on right side are sorted descending. So if v appears on both sides, there's no conflict. So effectively, for each value v < peak, we can contribute up to min(freq[v],2) to the total count. However, we might not be able to use all min(freq,2) simultaneously because we need to assign each copy to either left or right, and the left side must be strictly increasing, meaning that we must order the left side values ascending, and they can be any subset. Similarly right side values descending. There's no constraint linking left and right sets except that they both consist of values less than peak. So we can arbitrarily decide which values to put on left, which on right, and possibly both if we have two copies. So we can indeed achieve the total sum over v < peak of min(freq[v], 2) + 1 for peak. But what about the peak's frequency? We need exactly one peak. So we must have at least one card with value equal to peak. So we need to choose a peak value p such that freq[p] >= 1. Then total length = 1 + sum_{v < p} min(freq[v], 2). However, is this always realizable as a stair sequence? Let's test with examples.
Example 1: freq[1]=1,2=1,3=1,4=1,5=1. For any peak, if peak=5, sum_{v<5} min(1,2)=4, total=5. That matches output: 5 4 3 2 1 (they used decreasing only, i=1). If they had used peak=5 and left side increasing, they could also produce [1,2,3,4,5] but that would be increasing only (i=5) but that also is allowed. But they output decreasing order; that's fine. For peak=5, we can include all numbers. For other peaks, length would be smaller.
Example 2: numbers: 1,1,2,2,3,3. freq: 1:2, 2:2, 3:2. Let's compute for each possible peak:
p=1: sum_{v<1}=0, total=1. But we also could use p=1 and maybe have left side empty, right side can have values <1? none. So 1.
p=2: sum_{v<2}= min(freq[1],2)=2, total=1+2=3. But example output says max length is 5. So maybe p=3: sum_{v<3}= min(freq[1],2)+min(freq[2],2)=2+2=4, total=5. Indeed we get 5. So maximum is 5. Output: 1 2 3 2 1. That uses peak=3, left side: 1,2 (increasing), right side: 2,1 (decreasing). So left uses values 1 and 2 each once, right uses values 2 and 1 each once, total min(2,2) for both values. So works. So formula holds.
But is it always possible to arrange left and right to be strictly increasing/decreasing when we include both copies of a value on both sides? For value v appearing on both sides, left side includes v, right side includes v. In the sequence, left side ends at some point then peak then right side. The left side is strictly increasing: ... v ... peak? But careful: If v appears on left, and also appears on right, then after the peak, the right side starts with some value r1 which must be less than peak. Since v might be used on both sides, the left side's last element before the peak must be less than peak (obviously). The right side's first element after peak must also be less than peak. But if we have two copies of v, we can put v as the last element on left? Actually left side is increasing: all values are distinct and increasing. The left side values must all be less than peak, but they can be any order. Typically we would arrange left side in increasing order: a1 < a2 < ... < a_{i-1} < peak. So left side values are sorted ascending. The right side is decreasing: peak > a_{i+1} > a_{i+2} > ... So right side values are sorted descending. If we have v on both sides, then v will appear on left somewhere and on right somewhere. But note that on left side, v is less than peak and also less than any larger values to its right on left. On right side, v appears and it must be less than peak, and also greater than the next value to its right (since descending). The only potential conflict is that if v is the maximum among values less than peak, then on left side it would be the immediate predecessor of peak (the last element). On right side, v would be the first element after peak if it's the largest among right side values. However, that would create a situation: ... v, peak, v, ... But then we have peak > v, and then v > next? But if v is the largest on right side, then the right side would start with v, then some smaller values. This is allowed because peak > v and v > next, so it's fine. However, we must ensure that the left side's last element is strictly less than peak, which is true. But is there any rule that all values on left must be strictly less than all values on right? Not necessarily. The condition only requires the immediate inequalities: left sequence increasing, then peak, then decreasing. So left and right values can interleave; there is no condition relating a left value to a right value except through the peak. For instance, sequence [1,2,3,2,1] has left values 1,2 and right values 2,1. 2 is both left and right, but left's 2 is less than peak (3), and right's 2 is also less than peak. That's fine. So no conflict.
But could there be an issue when we have more than 2 copies of some value? For v < peak, we can use at most 2 copies (one on each side). If freq[v] >= 2, we can use both. If freq[v] > 2, we can only use 2 because any third copy would have to be placed somewhere but would break strictness. On left side, all values must be distinct, so you cannot have duplicate v on left. Similarly on right. So max usage per value is min(freq,2). So the formula seems right.
But there is nuance: The peak itself could also have freq > 1, but we can only use one copy as peak. Could we use additional copies of peak on sides? No, because sides require values strictly less than peak. So extra copies of peak cannot be used anywhere else because they would be equal to peak and would break strictness (since left side values must be < peak, right side values must be < peak). So they must be left unused. So effectively, we can only use one copy of the peak value.
Thus the problem reduces to: choose a value p (1 <= p <= 5000) such that freq[p] >= 1, and compute total = 1 + sum_{v=1}^{p-1} min(freq[v], 2). This gives the maximum possible length using peak p. Since we want to maximize total over all p, we can compute that easily with freq array.
But is there any scenario where we can get longer sequence by not using a peak that is the maximum value among those used? Could we have a stair sequence where the peak is not the maximum value in the multiset? For instance, suppose we have many copies of a high value but we use only one as peak; but maybe we could use some other values > peak? No, because any value > peak would have to be either on left or right, but left side must be strictly increasing to peak, so all left values < peak; right side must be strictly decreasing from peak, so all right values < peak. So any value greater than the peak cannot be included because it would violate the inequalities. So we cannot include numbers larger than the peak. So the peak must be at least as large as any number used. So if we want to include a large number, we need to set it as peak, otherwise it would be excluded. So the optimal peak likely is the maximum value present? Not necessarily, because while a larger peak allows inclusion of more numbers (since it allows values less than it), the peak value itself might have low frequency? But we only need one copy, so as long as freq[p]>=1, we can set it as peak. However, if there is a very high value with freq=1, and there are many values just below it with large frequencies, using that high peak might allow including all those below. That seems beneficial. Using a slightly lower peak would exclude the high value but that's okay because we can't include it anyway if it's > peak. However, could using a lower peak allow us to include some numbers that are equal to the high peak? No, because they are > lower peak, so cannot be included. So using the highest possible peak (i.e., the maximum value in the multiset) might yield the maximum sum because it includes the broadest range of values (all numbers less than that max). But there is a nuance: the sum of min(freq[v],2) over v < p increases as p increases (since we add more terms). So the total is non-decreasing as p increases? Not necessarily strictly because for higher p, we add min(freq[p-1],2) etc. So total is monotonic non-decreasing as p increases, because we add non-negative contributions. So the maximum total would be achieved by the maximum possible p (i.e., the maximum value present) provided freq[max] >=1 (which it is). But careful: We also have the term 1 for the peak. For p = max, we add 1 for the peak itself. For a smaller p, we omit contributions from values between p and max, but those values are > p, cannot be used anyway, so we don't count them. So yes, total length is sum_{v < p} min(freq[v],2) + 1. This is increasing as p increases because we include more values < p. So the maximum total occurs at p = max possible value (i.e., the maximum card number). However, we also need to consider that if the maximum value appears only once, we still use it as peak. But what if the maximum value appears many times? We still use one as peak. The rest cannot be used. So using maximum as peak is still optimal.
But wait: Could there be a scenario where using a lower peak yields a larger total because for some values v between that lower peak and the actual max, min(freq[v],2) might be 0 (i.e., freq=0) so not adding, but also we lose the ability to include the actual max, but that's only 1 card. So it's never beneficial to choose a lower peak because you can always choose a higher peak and at worst you add at least 0? But if the higher peak's freq is 0? But we can only choose peak if freq[peak]>=1. So if the maximum value appears with freq=0? That's impossible; by definition max is present. So picking a larger peak can only add contributions from values between old and new (which are non-negative) and also maybe we need to subtract something? No, because previously for smaller p, we didn't include those values because they were > p, so they were not allowed. So by increasing p, we allow to include them, but we also might be forced to include them? We are not forced; we can choose to not include some values even if allowed. In our formula we assume we include all possible min(freq,2) for v<p. That's optimal for a given p because including more cards always increases length. So for larger p, the maximum length is at least as large as for smaller p (since we can always ignore extra numbers? Actually if we increase p, we have the option to also include the new values; we don't have to include them, but including them increases length. So the optimal for larger p is at least as high as for smaller p (by taking same set as before plus maybe extra). So indeed the maximum over p is achieved at max value.
Thus the answer length is simply: L = 1 + sum_{v=1}^{maxVal-1} min(freq[v], 2). Where maxVal is the maximum number in the input (since we must set peak = maxVal). But is it always necessary to set peak = maxVal? Consider input: numbers: [1000, 1,1,1,1,... many ones]. Suppose maxVal=1000, freq[1000]=1, freq[1]=many, say 100. Then L = 1 + min(100,2) = 3. That's small. But if we set peak = 1, then L = 1 + sum_{v<1}=1. So still 1. But what if we set peak = some value that is not the maximum but that has high frequency? For example, numbers: [2,2,1,1,1]. max=2, freq[2]=2, freq[1]=3. Using peak=2: L = 1 + min(freq[1],2)= 1+2=3. Using peak=1: L=1 (since no v<1). So 3 is better. So max wins.
But consider numbers: [5,1,1,1,1,1]. max=5, freq[5]=1, freq[1]=5. L = 1 + min(5,2)=3. That's optimal. Could we do better by not using the 5 at all? But if we don't use 5, then the highest value we can include is 1 as peak, length=1. Not better.
So seems straightforward.
But wait, there is another nuance: What about values exactly equal to peak? Could we put them on the sides if we have a higher peak? No, because sides require < peak.
Thus, the answer is as above.
But let's test with more examples. Suppose input: [1,2,3,4,4,4]. freq: 1:1,2:1,3:1,4:3. Using peak=4: L=1 + sum_{v<4} min(freq,2) = 1 + min(1,2)+min(1,2)+min(1,2)=1+1+1+1=4. So we can form a stair of length 4, e.g., [1,2,3,4] increasing only, or [3,4,2,1]? Actually we need 4 cards: could be [1,2,4,3]? Check: 1<2<4>3? 4>3, yes. That uses 1,2,4,3. That's 4. Could we get length 5? We have three 4's, but only one can be used as peak. The other two 4's cannot be used because they are equal to peak, cannot go on sides. So maximum 4. Could we instead set peak=3? Then L = 1 + sum_{v<3} min(freq,2)=1+min(1,2)+min(1,2)=1+1+1=3. Worse.
So formula holds.
Now, we must also output an actual sequence that achieves this maximum length. So we need to construct a stair sequence using the cards optimally.
Construction: Choose peak = maxVal. For each value v < maxVal, we can use up to min(freq[v],2) copies. To maximize length, we will use exactly min(freq[v],2) copies. However, we need to assign them to left and right sides. The left side requires a strictly increasing sequence, right side strictly decreasing. Typically, we can take one copy of each value that has at least one occurrence and put it on the left in increasing order. For values that have two or more occurrences, we can also put one copy on the right. For values that have only one occurrence, we need to decide whether to put it on left or right. But to maximize length, we want to use as many cards as possible. For v with freq=1, we can only use it either on left or right, not both. So we need to decide allocation to maximize total length? But total length is fixed: for each v<maxVal, we include it up to min(freq,2). So if freq=1, we will include it exactly once. But we can choose to put it on left or right. That doesn't affect count. However we need to ensure that both left and right sequences are strictly monotonic. If we put all singleton values on left, we can do that; but then the right side might be empty. That's fine because a purely increasing sequence is allowed (peak at end). Or we could put some on right, but then left might have gaps. The only requirement is that left side is increasing and right side decreasing. There's no requirement that both sides must be non-empty; either can be empty.
Thus a simple construction: Let L be the list of values v < maxVal that have at least one occurrence. Sort them ascending. This will be the left side (each value appears once). This uses one copy from each v, regardless of freq. For the right side, we want to use an additional copy for each v that has freq >=2. Since we already used one copy for those v on left, we have an extra copy that can be placed on the right. The right side should be decreasing; so we can list those v that have freq >=2 in decreasing order. Also, what about v that have freq=1? They are already used on left, cannot be used again.
But is it necessary to put the v with freq >=2 on the left? Could we allocate the single copy to right instead and put the extra on left? As long as we ensure we use exactly one copy on left and one on right for those v with freq>=2, the assignment can be swapped. But the above approach is simple: use all distinct values on left increasing, then for each value with freq>=2, put one on right decreasing.
But wait: What if a value v appears with freq >=2 but also there is a value w that appears with freq=1; could we get a longer total by moving the singleton to right and using both copies of v on left? That wouldn't increase total length; we still use each value once on each side appropriately. The total number of used cards remains the same. The assignment just needs to produce a valid stair. The above method yields left side: all distinct values less than maxVal in increasing order. Right side: all values with freq>=2 in decreasing order. Check monotonicity: left increasing, obviously; right decreasing, obviously. Also need to ensure that left's last element (if any) is less than maxVal, which is true. Right's first element (if any) is less than maxVal, true. Also need to ensure that if a value appears on both sides, there is no conflict. The sequence would be: left values (sorted increasing), then maxVal, then right values (sorted decreasing). That is a valid stair. Example: freq: 1:2, 2:1, 3:2, max=3. left: [1,2] (since all v<3: 1 and 2, both at least one), right: values with freq>=2: 1 and 3? 3 is max, not included. So right: [1]? But we have two copies of 1, so we have one extra for right. Also we have 3? No, max only one used. So right: maybe [1]? But we also have value 2 with freq=1, used only on left. But 3 is max, freq>=2? Actually 3 has freq=2, but max is 3, we can only use one as peak, the other cannot be used. So right only includes v<3 with freq>=2: that is only 1. So right = [1]. Sequence: [1,2,3,1] ? Check: 1<2<3>1, okay. That's length 4. But we could potentially also include 3? No. total min(freq<3,2) = min(2,2)+min(1,2)=2+1=3 plus peak=1 ->4. So using left all distinct values includes 2 and 1, but that uses the only copy of 2 on left, and one copy of 1 on left. Then we have an extra copy of 1 for right. That's fine.
But what about values that have freq>=2 but we don't put them on left? In the above, we put all distinct values on left, so those with freq>=2 are included on left. That's okay because we have at least one copy. Then we have an extra for right. So it works.
However, there is a potential problem: What if we have a value v with freq>=2, but also there is a value w with freq=1 that is greater than v? In left side, we are listing all values in increasing order, so w would come after v. That's fine. For right side, we list v in decreasing order among those with freq>=2. Since w is not in right side, it's fine. Sequence left: ... v ... w ...; peak; right: ... v ... . After peak, right side starts with maybe something larger than v? But since right side only includes values with freq>=2, and they are sorted decreasing, the first element on right could be the largest among those with freq>=2. That largest might be greater than some values on left that are smaller, but that's irrelevant.
Thus construction is straightforward.
But wait, there is a nuance: Could this construction sometimes use more than min(freq,2) for a particular value? Let's count: For v with freq=1: we use exactly one copy (on left). Good. For v with freq>=2: we use two copies: one on left, one on right. That's min(freq,2). So it respects availability. However, we must ensure we actually have two copies available: one for left, one for right. If freq>=2, yes. So it's fine.
But there is a subtlety: If we include all distinct values less than maxVal on left, that uses exactly one copy of each value, regardless of freq. That's okay if freq[v]>=1 (by definition, if v appears). So left side length = number of distinct values less than maxVal. Right side length = number of distinct values v < maxVal with freq[v]>=2. So total length = 1 + distinct_less + count_ge2.
But earlier formula gave total = 1 + sum_{v<max} min(freq,2). Sum_{v<max} min(freq,2) = sum_{v<max} (1 if freq>=1 else 0) + sum_{v<max} (1 if freq>=2 else 0) = distinct_less + count_ge2. Indeed matches. So this construction yields optimal length.
But is it always possible to construct left side with all distinct values less than max? Yes, because we have at least one copy of each, and we can arrange them in increasing order. For right side, we need one extra copy for values with freq>=2, and we arrange them in decreasing order.
Thus the answer sequence: left part: all distinct numbers from 1 to max-1 that appear at least once, sorted ascending. Then peak: max. Then right part: all distinct numbers from 1 to max-1 that appear at least twice, sorted descending.
But careful: There might be values with freq>=2 that also appear only once? Actually freq>=2 means at least two copies. So they will appear in both left and right. For values with freq=1, they only appear in left. This construction yields a sequence where if a value appears twice, it appears both on left and right. That's allowed. So the output is valid.
Now we must check the sample: Input 6: 1 1 2 2 3 3. max=3, distinct less: 1,2 both appear -> left: [1,2]. Count_ge2: 1 and 2 both have freq>=2 -> right: [2,1] descending. Sequence: [1,2,3,2,1] -> matches sample.
First sample: 1 2 3 4 5, max=5, distinct less: 1,2,3,4 -> left: [1,2,3,4]. Count_ge2: none because each freq=1 -> right empty. Sequence: [1,2,3,4,5] which is increasing, also valid. But sample output is "5 4 3 2 1". That's also valid: it's decreasing only. Both have length 5. Our construction gave increasing; but any valid sequence is accepted. So we can output either. The problem likely expects any optimal stairs. So we can output our constructed sequence.
But we must ensure our constructed sequence uses exactly the maximum length. In some cases, the construction using all distinct values on left and those with freq>=2 on right yields the maximum. However, we need to consider if there is any scenario where using all distinct values on left might cause a conflict with right side ordering? No.
One more test: input: [2,2,2,1,1]? Actually m=5: numbers: 2,2,2,1,1. freq[2]=3, freq[1]=2. max=2? Actually 2 is max. distinct less: value 1 appears -> left: [1]. count_ge2: values with freq>=2 less than max: only 1? freq[1]=2 >=2, so right includes [1]. Sequence: [1,2,1]. That uses two 1's and one 2. But we have three 2's, only one used as peak. Could we use more? No, because extra 2's cannot be placed. So length 3. Could we achieve length 4? Let's see if any other arrangement: maybe use peak=1? Then length=1. So 3 is max. So our construction gives 3. Good.
Now, consider scenario where the max value has frequency >1. We use one as peak; extra copies are wasted. Could we ever get a longer sequence by not using the max as peak, but using a lower peak so that we can use multiple copies of the max on sides? No, because max cannot go on sides if it's larger than peak. So if we lower peak, we exclude the max altogether, but we might lose only 1 card (the peak) while maybe we can use more copies of some other value? But those other values are less than max, and we could also use them when max is peak. Actually if we set peak to a lower value, we cannot use the max at all. So we lose the ability to include the max (which is at most 1 card used as peak). But maybe by lowering peak we could use more copies of a value that is equal to the max? That's not possible. So max peak is always optimal.
But wait: What if the max value appears many times, say freq[max] is huge, e.g., 1000 copies. If we set peak = max, we use only one of them, and all other copies are wasted. Could we instead set peak to some value lower than max but that appears also many times, and then use some copies of the max? No, because max > peak, cannot be used. So the max copies would still be wasted. So again using max as peak uses at most 1 copy; the rest are wasted regardless. Could we maybe not use max at all and instead use another value as peak, but then we might be able to use that other value's multiple copies? But we can only use one copy as peak, extra copies of that peak value would be wasted similarly. So using max as peak is still best because it allows inclusion of all numbers less than max. Unless the max has very low freq (1) and there is some lower value with high freq that we could use as peak and also use its extra copies on sides? But if we use that lower value as peak, we cannot include the max, but we might still use the lower value's extra copies? Actually if we set peak = v < max, we can include min(freq[v],1) as peak, and for values < v, we include min(freq,2). Also, for v itself, we cannot use extra copies on sides because they are equal to peak, not allowed. So extra copies of v are wasted too. So it's similar. So the trade-off is: using max as peak includes max and all numbers less than max. Using a lower peak excludes max but also excludes numbers between v+1 to max. Since those numbers could have contributed min(freq,2) each. So it's clearly a loss unless those numbers have zero frequency. But if they have zero frequency, then they don't contribute anyway. But if max is the only number in that range and has freq=1, we lose 1 card by using max vs using lower peak, but we gain the contributions from numbers between v+1 and max-1? Actually if those numbers are absent, no gain. However, could there be a scenario where using max as peak forces us to exclude some numbers because of strictness? No.
Thus the maximum length is computed as described.
But hold on: What about the possibility of not using a peak at all? No, must have peak.
So algorithm:
Read m, read array b.
Compute frequency array f[1..5000] (since max bi <=5000).
Construct left list: all v from 1 to maxVal-1 where f[v]>=1, in ascending order. (We can iterate v from 1 to maxVal-1 and if f[v] > 0, add v to left).
Construct right list: all v from maxVal-1 down to 1 where f[v] >= 2, in descending order. (or collect list then reverse, but it's easier to iterate descending and if f[v]>=2 add to right; that yields descending order).
The sequence = left + [maxVal] + right.
Print length and the sequence (space-separated).
But wait: This construction might not use exactly min(f[v],2) for values that appear with freq>=2? Actually left includes v once, right includes v if f[v]>=2. So yes, it uses 2 if f[v]>=2, else 1 if f[v]>=1. That's min(f,2). So perfect.
But is there any scenario where using all distinct values on left could cause the left side to have duplicate values? No, because we only add each v once.
Now, what about values that appear with freq>=2 but we might want to put both copies on right and none on left? That would still use 2 copies but then left might be missing that value. But left would then be missing that value, which reduces left count by 1 but still uses 2 copies overall because right uses 2 copies? However, can we put two copies of the same value on the right? No, because right side must be strictly decreasing, so duplicates not allowed. So each value can appear at most once on each side. So if we want to use two copies of a value, we must place one on each side. So the only way to use two copies is exactly one on left and one on right. So our assignment is forced: for any value with freq>=2 that we want to use twice, we must allocate one to left and one to right. So our construction does that. For values with freq=1, we have to decide left or right, but can't use both. Placing on left is fine. Could we place some of them on right instead? Yes, but then we need to ensure left side remains increasing and right side decreasing. If we move some singleton values to right, we might have left missing those values, but we could still have left list of other values. However, we must ensure that the right side is decreasing and left side increasing. There's no requirement that left includes all values. So we could have a different partition. But our construction is simple and yields the maximum length.
But is there any scenario where using all distinct values on left might cause the sequence to not be stairs because of something like left side having a value equal to some value on right causing the sequence to not be strictly decreasing after peak? The condition only requires the right side to be strictly decreasing; it doesn't forbid values that also appear on left. So that's fine.
Thus the problem seems solved.
But wait: Let's double-check the definition: "a1 < a2 < ... < ai - 1 < ai > ai + 1 > ... > a|a| - 1 > a|a|". This means that the sequence is strictly increasing up to the peak, and strictly decreasing after. So duplicates across sides allowed. Our sequence left: increasing distinct, peak, right: decreasing distinct. That satisfies.
Now we need to consider if there are any edge cases:
m=1: then max is the only number, left empty, right empty. length=1, sequence = [that number]. This is both increasing (i=1) and decreasing (i=1). Works.
All numbers are the same: e.g., 2,2,2. max=2, freq[2]=3. left: values <2: none, so empty. right: values <2 with freq>=2: none. So sequence = [2]. length=1. Could we get longer? Possibly 2,2? But 2,2 is not stairs because need strict: either 2<2? No. 2>2? No. So only peak alone works. So output 1. Good.
Mixed: numbers: [1,2,3,3,3] max=3 freq[3]=3, freq[2]=1, freq[1]=1. left: [1,2], right: values with freq>=2 less than 3: none (2 has freq=1,1 has freq=1). So length = 1+2=3. Sequence: [1,2,3]. Could we use more? We have three 3's, but only one can be peak. So max 3. Could we do [2,3,1]? 2<3>1 works, length 3. Yes. So fine.
Now consider scenario where there are values less than max that have freq>2. e.g., max=10, freq[5]=5, others 0. left includes 5, right includes 5 (since freq>=2). sequence: [5,10,5]. length=3. Actually total min(freq[5],2)=2, plus peak 1 =3. That's max.
Now, what about values with freq>=2 but we may decide not to use both copies? That would reduce length, not beneficial.
Thus algorithm seems correct.
But before finalizing, we must verify if there is any hidden nuance: The problem says "Sereja has m cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table?" This implies we can choose any subset and arrange them arbitrarily. So indeed reordering allowed.
But wait: Could we possibly use a value more than twice if we place it on left and right and also as peak? Peak is distinct value, so if a value appears and we set it as peak, we cannot place it also on sides because sides require values < peak. So not allowed. So value can appear at most twice if it's less than peak, and at most once if it's the peak.
Thus the reasoning holds.
Now, complexity: m up to 1e5, values up to 5000, we can compute freq array of size maybe 5000+1. That's fine.
But we need to output the sequence. Our constructed sequence length L could be up to m, but might be less. However note that sum_{v<max} min(freq,2) could be up to 2*(maxVal-1) but maxVal <=5000, so L <= 1+24999=9999? Actually maxVal could be 5000, and there could be up to 5000 distinct values, each with freq at least 2? But m is up to 1e5, so L could be as high as m, but limited by m. Actually if all numbers are distinct from 1 to 5000, then L = 1+5000-1 = 5000. Because each min(freq,2)=1. That's 5000. But m could be 1e5, so there could be duplicates increasing L: For values less than max, if each freq >=2, then L = 1+2(maxVal-1). If maxVal=5000, that's ~9999, which is less than 1e5, so L <= ~10000. But m up to 1e5, but L is bounded by 25000+1 = 10001 because values only up to 5000. Actually number of distinct values is at most 5000, each can contribute at most 2. So maximum length of a stair sequence from numbers in range 1..5000 is at most 25000 - 1? Actually peak uses one distinct value, the rest can use at most two each, so maximum length = 1 + 2*(5000-1) = 9999? Wait distinct values possible: 1..5000 inclusive, that's 5000 distinct numbers. If we take max=5000, then we have values 1..4999 for sides, each can contribute up to 2, so total = 1 + 2*4999 = 9999. But also we could have values = 5000 appearing multiple times? No extra usage. So L <= 9999. But m can be 100k; however the maximum length is bounded by the distinct values, not by m. So answer length will never exceed about 10000. That's fine.
But wait: Is it possible that the max value is not the maximum among all numbers, but we can choose a peak that is not the overall max but maybe there are numbers larger that we don't use, and we can still use numbers less than that peak. But using a lower peak would only reduce possible distinct values to less than or equal to that peak. So maximum length is achieved by taking the overall maximum as peak. So L <= 1 + 2*(maxVal-1) <= 1 + 2*4999 = 9999. But what if maxVal is less than 5000? Then bound is smaller. So output length is at most 9999, far less than 1e5. So we can output easily.
But is it always optimal to take the overall max as peak? Yes, as argued. So algorithm is simple.
But wait: There is a nuance: The problem's example 2 output is 5 and sequence 1 2 3 2 1. That matches our construction (left: 1,2; peak:3; right: 2,1). So fine.
Now, we need to confirm that the construction indeed uses the available cards. For values with freq=1, we use that one copy in left. For values with freq>=2, we use two copies: one in left, one in right. But we must ensure that after using one copy for left, we still have at least one copy remaining for right. That's true if freq>=2. So we need to track usage. Since we are just outputting the sequence, we can just list the values; we don't need to physically deduct counts, as long as the multiset supports it. So it's valid.
One more test: Input: [1,1,1,2,2,3]. freq: 1:3,2:2,3:1. max=3. left: values<3 with f>=1: 1,2. So left: [1,2]. right: values<3 with f>=2: 1 and 2? f[1]=3>=2, f[2]=2>=2 -> right: [2,1] descending? Actually descending order: 2,1. So sequence: [1,2,3,2,1] length=5. But we have three 1's; we used two (one left, one right). One extra 1 not used. That's okay. Also we have two 2's; used both. So total used 5, matches length. Could we use all six? Let's see if we can form a stair of length 6? To use all, we would need to include the third 1 somewhere, but can't. So 5 is max. Good.
Now consider a case where there is a value v less than max with freq=1. That forces it to be used either left or right. Our construction puts it on left. But what if that value is very large, say just below max, and we have many other values with freq>=2? It's fine.
But is there any scenario where putting a singleton on left could cause a conflict with right side ordering? No, because left and right are independent.
Now, can we always output left part as sorted ascending? Yes.
Now, but we need to be careful: The left part must be strictly increasing. If we include all distinct values, it's automatically strictly increasing because they are distinct and sorted. Right part is strictly decreasing because we sort descending and they are distinct.
Thus algorithm works.
But let's verify with a slightly more complex case: Suppose frequencies: 1:1, 2:1, 3:2, 4:2, 5:1, max=5. Our construction: left: [1,2,3,4] (since 5 is max, all less with freq>=1). Right: values with freq>=2 less than 5: 3 and 4. Right descending: [4,3]. Sequence: [1,2,3,4,5,4,3]. Check: 1<2<3<4<5>4>3. Works. Length = 1 + (min1,2 for 1..4) = 1+(1+1+2+2)=7. Indeed 7.
But wait: Did we use two copies of 3 and 4? left includes 3 and 4, right includes 4 and 3. So we used two copies each. Good.
Now, could there be a case where we have value v with freq>=2 but also v is the only value less than max? Then left includes v, right includes v. Sequence [v, max, v]. That's valid.
Now, consider if max value has freq=0? Not possible.
Thus solution is straightforward.
But let's read the problem statement again to ensure no misinterpretation: "Sereja has m cards with numbers. He wants to put some cards on the table in a row to get a stair sequence. What maximum number of cards can he put on the table?" The phrase "put some cards on the table in a row" might imply we can arrange them in any order, but could it imply we must preserve the original order? Typically in such problems (like Codeforces problem "Sereja and Stairs" maybe), you are given a multiset and you need to arrange them to form a "stairs" (strictly increasing then strictly decreasing). I recall a known Codeforces problem: "Sereja and Stairs". Actually I think this is Codeforces Round #... Yes, there's a problem "Sereja and Stairs". The solution is exactly as described: take all distinct numbers in increasing order, then the maximum, then all numbers that appear at least twice in decreasing order (except the max). So it's exactly our construction. So it's solved.
Thus implement.
Edge Cases: If the max value appears, but there are also other values equal to max? We ignore extras.
Now, we also need to print the number of cards and the resulting stairs. The output format: first line number of cards, second line the sequence (space-separated). If there are multiple answers, any is accepted.
Thus we can code.
But wait: Need to consider if there is any scenario where using all distinct numbers on left might cause the sequence to not be valid because the left side includes a value that is also on right and that might cause the right side to not be strictly decreasing if there are duplicate values? But right side only includes each value once, sorted descending, so it's fine.
Now, confirm with an example: Input: [1,2,2,3]. freq: 1:1,2:2,3:1. max=3. left: [1,2] (since 2 appears, we include once), right: values with freq>=2: 2. So sequence: [1,2,3,2]. That's stairs. Length=4. But can we use the extra 2? We already used both copies? Actually freq[2]=2: one used on left, one on right. So used both. So total cards used = 1 (1) + 2 (two copies of 2) + 1 (3) =4. That's all cards? Actually input has 4 cards: 1,2,2,3. So we used all! That's maximum possible length. Good.
If we had [1,2,2,2,3] freq:1:1,2:3,3:1. max=3. left: [1,2], right: [2] (since 2 freq>=2). Sequence: [1,2,3,2]. length=4. But we have 5 cards; we can't use the third 2. Could there be a stair of length 5? To use 5 cards, we would need to use three copies of 2, but only two can be used (one left, one right). So 4 is max. Good.
Thus algorithm yields maximum.
Now, what about the scenario where there is no value that appears at least twice? Then right is empty, sequence is just increasing order of all distinct values plus the max? Actually left includes all distinct values less than max, sorted. Since max is the largest, that yields increasing sequence. Alternatively, we could output decreasing sequence. Our construction gives increasing. That's fine.
Now, but there is a nuance: The problem might require the output to be a valid stair where the peak is strictly greater than both neighbors. For increasing only (peak at end) it's allowed because i=|a| means condition becomes a1 < a2 < ... < a_n, which is a stair. Similarly decreasing only.
Now, code: We'll create an array freq of size maybe 5001 (since values up to 5000). We'll read m and list b. Compute freq and maxVal.
Compute length: start with 1 (for peak). Then for v=1 to maxVal-1: if freq[v] >= 2: length += 2; else if freq[v] == 1: length += 1; else 0.
Better: length = 1 + sum(min(freq[v],2) for v in 1..maxVal-1).
Construct left list: iterate v from 1 to maxVal-1: if freq[v] > 0: append v to left. This uses one copy.
Construct right list: iterate v from maxVal-1 down to 1: if freq[v] >= 2: append v to right. (This yields descending order)
Then final sequence = left + [maxVal] + right.
Print length = len(sequence) (should equal computed length) and the sequence.
But careful: The computed length may be different from len(sequence) if we miscount? Let's ensure: len(left) = count of v with freq[v]>0 for v<maxVal. len(right) = count of v with freq[v]>=2 for v<maxVal. So total length = 1 + len(left) + len(right). And sum min(freq,2) = for each v<max: if freq=0 => 0; if freq=1 => 1; if freq>=2 => 2 => that equals 1+? Actually for v with freq>=2, min=2, which can be expressed as 1 (for left) + 1 (for right). So sum = len(left) + len(right). Yes.
Thus length matches.
Now, note: In left construction, we include v regardless of freq>=2 or =1. That's correct. For v with freq>=2, we use one copy on left. For right, we add another copy. So all good.
Now, we must be careful about the case where maxVal appears with freq>=2 and also there are values less than max that appear? That's fine.
Now, implement.
But wait: There's a known nuance: In some Codeforces editorial, they suggest to output all numbers in increasing order except those that appear more than once (except one) are put in decreasing order after the max. Actually they often output: first print all numbers from 1 to max that appear at least once (in increasing order), then print all numbers from max-1 down to 1 that appear at least twice (in decreasing order). That's exactly our construction.
Now, confirm with the sample: input 1: 1,2,3,4,5 -> left: [1,2,3,4], right: none (since none have freq>=2). So sequence: [1,2,3,4,5]. The sample output is "5 4 3 2 1". Our output would be "1 2 3 4 5". Both are acceptable. So we can output our constructed one. But to be safe, we could also optionally output decreasing if we want, but easier to output increasing. However we must ensure the peak is the maximum. In increasing sequence, the peak is the last element. That's allowed. So fine.
Now, test with an input where max appears multiple times: e.g., [2,2,1]. Our construction: max=2, left: v<2 with freq>0: v=1 (freq=1) => left=[1]; right: v<2 with freq>=2: none; sequence=[1,2]. length=2. But we have three cards. Could we make length 3? Try to use all three: [1,2,2]? Not stairs because 2 not >2. [2,1,2]? 2>1<2 not stairs. [2,2,1]? 2 not >2. So max 2. So output length 2, sequence [1,2] or [2,1]? Our output is [1,2]. Good.
Now, test [2,2,2,1,1]: max=2, left: [1], right: [1] (since freq[1]=2>=2). Sequence [1,2,1] length=3. Check if we can get length 4? Use [1,2,2,1]? 1<2<2 not strictly increasing. So no. So 3 is max.
Now, one more: [1,2,3,3,2,1]? freq:1:2,2:2,3:2. max=3. left: [1,2]; right: [2,1] (since 1 and 2 have freq>=2). Sequence: [1,2,3,2,1] length=5. Could we get 6? Use all six? [1,2,3,3,2,1]? Check: 1<2<3<3 not strictly increasing (3<3 false). So no. So 5 max.
Thus algorithm seems correct.
Now, edge case: What if maxVal = 1? Then there are no values less than 1. left empty, right empty, sequence [1]. length=1. Good.
Now, the problem's constraints allow m up to 1e5, but we only need to store up to 5000 freq. So memory fine.
Now, I'll implement solve().
Implementation steps in Python:
def solve():
import sys
input = sys.stdin.readline
m = int(input().strip())
b = list(map(int, input().split()))
max_val = max(b)
freq = [0] * (5001) # or max_val+1, but since values up to 5000, allocate 5001.
for x in b:
freq[x] += 1
# Compute length and construct lists
left = []
right = []
for v in range(1, max_val):
if freq[v] > 0:
left.append(v)
for v in range(max_val-1, 0, -1):
if freq[v] >= 2:
right.append(v)
seq = left + [max_val] + right
# length = len(seq)
print(len(seq))
print(' '.join(map(str, seq)))
That's it.
But wait: There's a nuance: In the left list, we include v if freq[v] > 0. However, what if freq[v] is huge but we only need one? That's fine.
Now, verify: If max_val is something like 5000, we iterate from 1 to 4999 for left, and from 4999 down to 1 for right. That's fine.
Now, but what about values greater than max_val? There aren't any. So fine.
Now, consider if there are values less than max_val with freq=0, we skip.
Now, is it always optimal to include all distinct values on left? Suppose we have a value v with freq=1, and we put it on left. That's fine. Could there be a scenario where putting it on left would cause the sequence to not be strictly increasing because left side includes values that are not sorted? But we sort them, so it's fine.
Now, is there any scenario where using all distinct values on left results in a left side that has a value that is also on right, but that causes the sequence to have two identical values adjacent? They are separated by peak, so not adjacent.
Thus fine.
Now, one more potential twist: The problem might require the sequence to have exactly one peak (i index). In increasing only, i = |a|, so it's fine. In decreasing only, i=1. So both allowed.
Now, confirm with an example where the maximum value appears, but there is a value less than max that appears only once and we might want to put it on right instead of left to make the sequence more balanced? Not necessary.
Thus solution is done.
But wait, I recall a known Codeforces problem "Sereja and Stairs" (CF 381A maybe? Actually it's 381A? Not sure) The solution is exactly this.
Double-check: I think there is a known edge case: If the maximum value appears multiple times, we cannot use the extra copies. So the answer may be less than m.
Now, ensure we output the number of cards in the first line, then the sequence.
Now, I'll produce final answer.
But before finalizing, let's test with random small cases manually by brute force to ensure our construction yields optimal length. Could there be a scenario where we can get longer than 1 + sum(min(freq<max,2))? Perhaps by using a peak that is not the maximum but we can use extra copies of the max on sides? No, because sides require < peak. So max cannot be used if it's > peak. So if we use a lower peak, we lose the max but could we possibly use some numbers > lower peak? No. So total possible for a given peak p is 1 + sum_{v<p} min(freq[v],2). Since p <= maxVal, this sum is largest when p = maxVal because we sum over more v. So indeed maxVal gives largest sum.
But wait, what about using a peak that is less than maxVal but maybe we could also use some numbers equal to maxVal on sides by lowering the peak? They are > peak, cannot. So no.
Thus optimal is with p = maxVal.
Now, could we use some numbers equal to the peak on the sides if we use the peak value that appears multiple times? No, because sides require strictly less.
Thus answer is correct.
Now, let's think about potential pitfalls: Input may have numbers > 5000? Problem says 1 ≤ bi ≤ 5000. So fine.
Implementation details: Use sys.stdin.read perhaps for speed, but not necessary.
Now, a nuance: The left list includes all values v < maxVal with freq>0. But what if we have a value v that appears, but we decide not to include it to avoid something? Since including it always increases length, it's beneficial.
But is it always possible to include all such v? The left side must be strictly increasing, so we need to have a distinct increasing order. Since all v are distinct values, we can include them all in increasing order. So yes.
Now, for right side, we include all v with freq>=2. That also increases length, and they are distinct values, we can arrange them in decreasing order.
Thus maximum.
Now, but what about a value v with freq>=2, we include one on left and one on right. But what if including that v on left would cause left side to have a value that equals something? No conflict.
Now, one more test: Suppose freq[1]=1, freq[2]=1, freq[3]=1, freq[4]=100. max=4. Our construction: left: [1,2,3], right: values with freq>=2 less than 4: none (since 3 has freq=1, 2,1 freq=1). So sequence [1,2,3,4] length 4. Could we do better? Maybe we can use some of the many 4's as something? But they are equal to max, cannot be used on sides. Could we set peak=3 instead? Then we could use both 4s? No, because 4 > 3 can't be used. So still 4 max. So length 4 is max.
Now, what about if we have freq[1]=2, freq[2]=2, freq[3]=2, max=3. Our construction: left: [1,2], right: [2,1] -> sequence [1,2,3,2,1] length 5. But we have 6 cards? Actually freq sum = 2+2+2=6. We used 5. Could we get 6? To use 6, we would need to use all three copies of 3? But only one can be peak, other two 3's cannot be used because they are equal to peak. So max 5. So our construction uses all except one extra 3 (since freq[3]=2 we used one, left one extra). But we used both 1's and both 2's. So that's max.
Now, one more scenario: freq[1]=2, freq[2]=1, freq[3]=2, max=3. left: [1,2]? Wait v<3 with freq>0: 1 and 2. So left = [1,2]. Right: v<3 with freq>=2: 1 (since freq[1]=2) and also? 2 has freq=1, 3 is max. So right = [1]? Actually descending: v from 2 down to 1: 2 freq>=2? no; 1 yes. So right = [1]. Sequence: [1,2,3,1] length 4. But total cards: freq sum=2+1+2=5. We used 4. Could we get 5? Let's see if we can include the extra 3 somewhere? But 3 is max, can't be on sides. So only one 3 used. What about the 2? We used it on left. Could we use the extra 1 on right? We already used both 1's (one left, one right). So all copies of 1 and 2 used, except one 3 unused. So 4 is max. Could we do a different arrangement to include the extra 3? No. So 4 is max. So our construction optimal.
Now, consider scenario: maxVal is not unique? Already covered.
Now, what about values that are not contiguous? It doesn't matter.
Thus solution stands.
Now, I'll write final code.
But let's also think about a scenario where the maximum value appears only once, but there is a value just below it that appears many times. Our construction uses that value on left and, if freq>=2, also on right. That's good.
Now, I'll produce final answer.
Implementation details: To avoid building lists that could be large (up to ~10000), fine.
Now, possible pitfalls: When max_val = 1, range(1, max_val) is empty, so left empty, right empty. So sequence = [1]. Good.
When max_val = 0? Not possible.
Now, test with a custom input:
3
2 1 2
Our code: max=2, left: values<2 with freq>0: 1 (freq[1]=1) -> left=[1]; right: v from 1 down to 1: freq[1]>=2? no, so right=[]; seq=[1,2]; length=2. But we have three cards: two 2's, one 1. Can we get length 3? Sequence [1,2,2] invalid; [2,1,2]? 2>1<2 not stairs; [2,2,1]? 2 not >2. So max 2. Good.
Now, test:
4
2 2 1 1
max=2, left: [1]; right: [1] (freq[1]=2) -> [1,2,1] length=3. Can we get 4? [1,2,2,1]? 1<2<2 invalid; [2,1,2,1]? no; [2,2,1,1]? no. So 3 max. Good.
Now, test:
5
3 3 2 2 1
max=3, left: v<3 freq>0: 1,2 -> left=[1,2]; right: v<3 freq>=2: 2? freq[2]=2 yes, 1? freq[1]=1 no, so right=[2]; seq=[1,2,3,2] length=4. Could we get 5? Use both 3's? No. So 4 max.
Now, test:
5
1 2 3 4 4
max=4, left: v<4 freq>0: 1,2,3 -> left=[1,2,3]; right: v<4 freq>=2: none (3 freq=1,2=1,1=1) -> seq=[1,2,3,4] length=4. Could we get 5? Use the other 4? Can't. So 4 max.
Now, test:
5
1 1 2 3 4
max=4, left: 1,2,3 -> left=[1,2,3]; right: v<4 freq>=2: 1 (freq=2) -> right=[1]; seq=[1,2,3,4,1] Check: 1<2<3<4>1 -> valid length=5. Actually we used all 5 cards: two 1's, one 2, one 3, one 4. Yes! That's maximum. Our construction yields length 5. Good.
Thus algorithm passes many tests.
Now, we should also consider if there is any scenario where using all distinct values on left could cause the left side to include a value that we later also include on right, but we might not have enough copies? For v with freq=2, we use one on left and one on right, so it's fine. For v with freq>2, we still use only two copies, so we have at least two copies available. So no shortage.
Thus code ready.
But wait: There is a nuance: The left list uses values in ascending order. But what about values that are not present? We skip.
Now, we must ensure that we output the number of cards first. That's len(seq).
Potential pitfalls: For large m, reading input may be heavy, but fine.
Now, final answer.
Let me also think about alternative solutions: Some might propose to sort the array and then output distinct numbers in increasing order and then duplicates (except one) in decreasing order after the maximum. That's essentially same.
Now, I will produce the final code.
But before final, let's search memory: There is known Codeforces problem 381A? Actually I recall "Sereja and Stairs" is from Codeforces Round #... It might be problem 381A? No 381A is "Sereja and Dima". Maybe "Sereja and Stairs" is 381B? Let's think: I recall a problem "Sereja and Stairs" (CF 381B). Actually I think it's Codeforces 381B. Yes, "Sereja and Stairs" is Codeforces 381B (maybe). The solution described matches. So we are good.
Now, check the constraints: In that problem, m up to 10^5, bi up to 10^5? Actually the problem says up to 10^5 and bi up to 10^5? But here it says up to 5000. The problem statement we have says 1 ≤ bi ≤ 5000. So it's a variation? Possibly from an older contest? Nonetheless, it's fine.
Now, finalize.
But just to be thorough, let's check if any tricky edge: Suppose the maximum value appears many times, and also there are many values less than it with high frequency. Our algorithm yields a sequence that might not be the longest possible if we decide to exclude some distinct values from left to allow more on right? No, because right only includes those with freq>=2, and using a distinct value on left doesn't affect right capacity for that value if freq>=2: we still can put it on right. So no trade-off.
Thus final.
Now, implement.
Also, we need to be careful: In Python, reading input using sys.stdin.read may be faster. But we'll keep it simple.
Now, code:
import sys
def main():
data = sys.stdin.read().strip().split()
if not data:
return
m = int(data[0])
b = list(map(int, data[1:1+m]))
max_val = max(b)
freq = [0] * (5001) # index 0 unused
for x in b:
freq[x] += 1
left = []
right = []
for v in range(1, max_val):
if freq[v]:
left.append(v)
for v in range(max_val-1, 0, -1):
if freq[v] >= 2:
right.append(v)
seq = left + [max_val] + right
print(len(seq))
print(' '.join(map(str, seq)))
if name == "main":
main()
That should work.
Now, verify with given examples:
Input:
5
1 2 3 4 5
Our output:
5
1 2 3 4 5
But sample output is "5 4 3 2 1". Both are valid. So likely accepted.
But we should double-check the second output: Our right list: values from max-1 down to 1 with freq>=2: 2 and 1 -> right = [2,1]. Sequence = left [1,2] + [3] + [2,1] = [1,2,3,2,1]. Good.
Now, ensure that we correctly handle when max_val is 1: left empty, right empty, seq [1], length 1.
Now, one more test: If max_val is large but some values less than max_val have freq=0, we skip them. That's fine.
Now, potential issue: The problem might require that the sequence must be a "stairs" as defined, and they might require that the peak is strictly greater than both neighbors. In the case of increasing only, the peak is the last element, and there is no neighbor on the right, so condition is satisfied? The definition: "there is such index i (1 ≤ i ≤ |a|), that the following condition is met: a1 < a2 < ... < ai - 1 < ai > ai + 1 > ... > a|a| - 1 > a|a|." For i = |a|, the condition becomes a1 < a2 < ... < a_{|a|-1} < a_{|a|} (since there is no ai+1). But the statement "ai > ai+1 > ..." part is vacuously true? Typically, yes. In mathematics, a sequence with i = n is considered strictly increasing, and it satisfies the definition because the decreasing part is empty. Similarly i=1 yields strictly decreasing. So it's allowed.
Thus our sequence is valid.
Now, we can output.
But I should check if there is any possibility that the computed length might be larger than m? No, because sum_{v<max} min(freq[v],2) + 1 ≤ sum_{v<max} freq[v] + 1? Actually min(freq,2) ≤ freq, but sum of min could be less than or equal to sum of freq, but note that we also have the peak from max, which might have freq≥1. So total used ≤ sum freq = m. So length ≤ m. So fine.
Now, final code.
But wait: There is a nuance: The problem might have a constraint that bi ≤ 10^5 but we only have 5000, but we'll allocate 5001.
Now, final answer.
Now, I'll produce the final response with explanation and code. ```python
import sys
def main() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
m = int(data[0])
cards = list(map(int, data[1:1 + m]))
code
max_val = max(cards)
freq = [0] * 5001 # numbers are ≤ 5000
for x in cards:
freq[x] += 1
# left part: all numbers < max_val that appear at least once, in increasing order
left = [v for v in range(1, max_val) if freq[v] > 0]
# right part: numbers < max_val that appear at least twice, in decreasing order
right = [v for v in range(max_val - 1, 0, -1) if freq[v] >= 2]
stair = left + [max_val] + right
print(len(stair))
print(' '.join(map(str, stair)))