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}.
Asked
Active
Viewed 288 times
4
-
Weakly or strictly monotone? – Coolwater Nov 03 '18 at 19:13
1 Answers
4
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}}
m_goldberg
- 107,779
- 16
- 103
- 257