I'm plotting data in matplotlib that the user can interact with via a lasso, which is internally represented as a list of vertices that make up a polygonal chain. What I would like to be able to do is to trim lassos as illustrated in this highly professional picture:
Formally, I have a list of vertices in the Euclidean plane, and I would like to find two vertices that are not adjacent in the list such that
their difference in both x and y direction is each below a certain threshold (I was thinking 1% of the axis range visible in the the figure where I'm lassoing)
the number of vertices lying between them in the list is maximized
If no such pair exists, the lasso will be discarded altogether.
The naive approach is O(n^2)
, where n
is the length of the list: for each number of vertices 1 ≤ i ≤ n - 2
, check each pair of vertices exactly i
indices apart, and for the highest i
where a suitable pair exists, select the first pair that is found.
That might even be tolerable complexity-wise since some basic tests showed that the lassos will rarely exceed 500 vertices, and more than roughly 1000 can probably be ruled out altogether. Still, it seems to me I should be able to do better than this.
Is there an algorithm that runs in less than O(n^2) and finds the indices of the desired pair, if it exists?