Longest subsequence in O(n)

C++ tested