Longest Increasing Subsequence 4
InterviewTime limit1sMemory limit256 MB
Find a longest strictly increasing subsequence of A, and among all of maximum length output the lexicographically smallest one along with its length.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Binary search, Greedy, Array
- Solved
- No attempts yet
Problem
A sequence is given. Pick some elements of , keep their original order, and join them: the result is a subsequence of . If the values of that subsequence always grow from left to right, it is an increasing subsequence.
Write a program that finds a longest increasing subsequence of and prints its length together with its elements.
For example, if , a longest increasing subsequence takes the first, second, fourth, and sixth elements, giving with length .
There can be several increasing subsequences of maximum length. In that case only the lexicographically smallest one counts as the answer. Between two sequences of the same length, compare values from the front: the one with the smaller value at the first position where they differ is lexicographically smaller.
Input
The first line contains the length of the sequence . ()
The second line contains the elements separated by spaces. ()
Output
Print the length of a longest increasing subsequence of on the first line.
Print the elements of that subsequence on the second line, in order, separated by single spaces. If several increasing subsequences have the maximum length, print the lexicographically smallest one.