HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Longest subsequence such that A[i].x < A[i+1].y

Submitted by: @import:stackexchange-cs··
0
Viewed 0 times
suchlongestsubsequencethat

Problem

I have an issue for which I am looking for an algorithm (if it exists)

What I have:
An array of items which have certain properties, e.g. item $A$ has properties $x$ and $y$.

Example: $[ A(x,y), B(x,y), C(x,y), D(x,y), E(x,y) ]$

What I want:
A result list consisting of elements of the original list, such as $[ A(x,y), C(x,y), E(x,y) ]$, for which the following properties are true:

  • No reordering of elements, they are in the same order as the original list



  • The result has the maximum number of elements, i.e. the longest 'path' possible



  • For each pair of consecutive items $(A(x,y), B(x,y))$ in the result, $A.x \lt B.y$. In other words, an item's $x$ must be less than the next item's $y$.



Complexity: The list in the case I have is about 35 items long, so an algorithm which is $O(n!)$ might not work.

Does such an algorithm exist?

Solution

It's easier to change notation. Suppose the array is $A$, with the $i$-th element denoted $A[i]$ for $i=1,2,\dots,n$, and that element $i$ has attributes $A[i].x$ and $A[i].y$. Associate a directed graph $G$ with the array as follows. The vertices of $G$ are the indices $1\dots n$ of the array. Vertex $i$ is connected to vertex $j\ $ if both conditions $i<j$ and $A[i].x < A[j].y\ $ hold.

You are then asking for a longest directed path in $G$.

Note that $G$ is actually acyclic, since the arcs form a subset of the usual order on the set $\{1,\dots,n\}$.
Any standard linear algorithm can then be used to compute the longest path, such as a topological sort.

Context

StackExchange Computer Science Q#12764, answer score: 5

Revisions (0)

No revisions yet.