Given an integer array nums, return the length of the longest strictly increasing subsequence.
Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Input: nums = [0,1,0,3,2,3]
Output: 4
Input: nums = [7,7,7,7,7,7,7]
Output: 1
Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?
The idea is to use a dynamic programming table to keep track of the length of the longest increasing subsequence that ends with the element at each position in the array. At each element, we consider all previous elements and find the longest subsequence that this element can extend.
dp array where dp[i] represents the length of the longest increasing subsequence that ends at index i.dp[i] to be the maximum of its current value or dp[j] + 1 where j is an index before i.dp array.Instead of maintaining an array to find the longest increasing subsequence with a direct comparison which results in O(n^2) complexity, we can use a clever trick involving binary search. The approach is to maintain an array that keeps the "minimal" possible tail for all increasing subsequences of various lengths. This makes the time complexity significantly better.
tails where tails[i] represents the smallest tail value of all increasing subsequences of length i+1.tails array.tails array: if the number is larger than the largest element in tails, append it.tails will be the length of the longest increasing subsequence.