Description
Given an integer array nums
, return the length of the longest strictly increasing
subsequence
.
Example 1:
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.
Example 2:
Input: nums = [0,1,0,3,2,3] Output: 4
Example 3:
Input: nums = [7,7,7,7,7,7,7] Output: 1
Constraints:
1 <= nums.length <= 2500
-104 <= nums[i] <= 104
Follow up: Can you come up with an algorithm that runs in O(n log(n))
time complexity?
Code
DP
Greedy with binary search O(n \log n)
res
為 increasing sequence。
對於 num[i]
來說,有兩種情形,一種是它比 res
的尾端大,那就直接 insert。
第二種情形是它比 res
的尾端小,就必須找到 res
中比它大的最小元素,將之取代。
取代比之大的最小元素及為 greedy choice,因為 num[i]
比較小,因此取代了之後所會造成的可能的 increasing sequence 只會更長不會更短。
其中 binary search 可以使用 std::lower_bound
。