1

We can use a stack to keep recording increasing subsequences while iterating the array. The run time is linear because each element enters and leaves the stack once.

If we want to output the actual sequence instead of its length, we can record the starting index, and then find all elements after it with greater values.

Does this linear time algorithm work?

    public int longestIncreasingSubsequence(int[] seq) {
    int longest = 0;
    int curSize = 0;

    LinkedList<Integer> stack = new LinkedList<Integer>();

    for (int i : seq) {
        while (!stack.isEmpty() && i <= stack.get(0)) {
            stack.removeFirst();
            curSize--;
        }
        stack.addFirst(i);
        curSize++;
        if (curSize > longest) {
            longest = curSize;
        }
    }

    return longest;
}
Niklas B.
  • 92,950
  • 18
  • 194
  • 224
zhe
  • 11
  • 1

1 Answers1

1

No. The algorithm you've written is not correct.

Consider the test case: 15,20,12,25

After two pushes:
stack: 20,15
curSize: 2
longest: 2

In comes 12. So two pops.
curSize: 0

12 pushed:
stack: 12
curSize: 1
longest: 2

25 pushed:
stack: 25,12
curSize: 2
longest: 2 //so gives answer 2

But in reality the answer should be 3.

HelloWorld123456789
  • 5,299
  • 3
  • 23
  • 33