I have a list, say {5,4,10,16,2,1}. I want the longest monotone subsequence. In this case the longest monotone sequence is {5,4,2,1}.
1 Answer
$\begingroup$ $\endgroup$
The following function will find the longest ascending or the longest descending monotonic sequence in a list of numbers. When the longest ascending sequence is of the same length as the longest descending sequence, it returns both.
longestMonotonicSeq[data : {_?NumberQ ..}] := Module[{up, down}, up = LongestOrderedSequence[data, #1 >= #2 &]; down = LongestOrderedSequence[data, #2 >= #1 &]; Switch[Sign[Length[up] - Length[down]], 1, up, -1, down, 0, {up, down}]] Tests
longestMonotonicSeq[{5, 4, 10, 16, 2, 1}]
{5, 4, 2, 1}
longestMonotonicSeq[{10, 11, 3, 25/2, 2, 1, 20, 42.}]
{10, 11, 25/2, 20, 42.}
longestMonotonicSeq[{10, 3, 16, 2, 1, 17, 20}]
{{3, 16, 17, 20}, {10, 3, 2, 1}}