Arrays and strings · Exercise 14 of 100
Longest Increasing Subsequence
An increasing subsequence keeps values in their original order, may skip slots and requires each chosen value to be strictly larger than the previous one. At each slot, start with length one and check earlier slots with smaller values. Extending the longest sequence from any such slot gives the best length ending here.
Try it yourself
What is the length of the longest strictly increasing subsequence in [3, 1, 4, 2, 2, 5, 6]?
One-step hint
Under each value, write the longest length ending there. Start at one and extend only from an earlier, strictly smaller value.
Worked solution
- For the first five slots the best ending lengths are 1, 1, 2, 2 and 2. Either 2 can follow 1, but equal values cannot extend one another.
- The 5 extends a length-two sequence to length three, and 6 extends that to four. The largest ending length is 4, achieved by 1, 2, 5, 6.