For instance, given the list [5, 9, 1, 2, 7, 8], the algorithm should find subsequences such as [5, 9, 7] or [5, 9, 8].
I need the algorithm to be efficient. One approach could involve tracking the maximum and minimum values while iterating through the list. Whenever a number falls between the current maximum and minimum, it's a potential candidate. However, this approach may fail in certain scenarios like this:
Consider the list [5, 8, 10, 2, 4]. The algorithm might suggest [2, 10, 4] as a solution, but it violates the restriction that the lowest value must precede the highest.
Do you know of a solution that works? Thank you.
You could use this approach:
Implementation in runnable JavaScript snippet:
As a value can only be pushed once on the stack and popped once from it, this algorithm has a O() complexity.