4
$\begingroup$

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}.

$\endgroup$
1
  • $\begingroup$ Weakly or strictly monotone? $\endgroup$ Commented Nov 3, 2018 at 19:13

1 Answer 1

4
$\begingroup$

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}}

$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.