I'm interested in finding the longest monotonically increasing subsequence of a sequence containing the final two elements. This question addresses my question without the italicized requirement. For example, given {3,4,6,7,5,8}
, the function should return {3,4,5,8}
, not {3,4,6,7,8}
. (In fact, I only need the length of that longest subsequence, but a function returning the subsequence is fine too.)
We may assume that lst[[Length@lst-1]] < Last@lst
and that the elements of lst
are distinct.
EDIT: Note that this is the same problem as determining the longest increasing subsequence including the final element - given such an algorithm, apply it to Rest@lst
to get the longest increasing subsequence containing the last two elements.
Answer
Using Leonid Shifrin's solution from the Q&A you mentioned:
longestSequence[{seq___, a_, b_}] := With[{list = Select[{seq}, # < a &]},
Join[LongestCommonSequence[list, Sort@list], {a, b}]
]
Comments
Post a Comment