Given an integer array nums, return the length of the longest strictly increasing subsequence.
[10,9,2,5,3,7,101,18]4Patience sorting: maintain pile tops. Each number goes on leftmost pile whose top ≥ it (binary search). If larger than all, new pile. Number of piles = LIS length.
There are 2 to the power n subsequences, so checking all of them is hopeless. Instead, remember the best answer that ends at each position.
Let dp of i be the length of the longest increasing subsequence that ends exactly at index i. Every element alone is a subsequence of length 1. For each earlier index j with a smaller value, you can extend that subsequence by the element at i. So dp of i is 1 plus the largest such dp of j. The answer is the largest value anywhere in dp.
Define dp as the best answer ending at i. The final answer is the maximum over all i, not dp of the last index.
Run the animation above on your own input, or watch the 1:58 video explanation of Longest Increasing Subsequence with a dry run and Java code.