Longest Increasing Subsequence
Difficulty: Medium · Pattern: 1-D Dynamic Programming · LeetCode #300
Return the length of the longest strictly increasing subsequence of nums. A subsequence keeps the original order but may skip elements.
Examples
text
nums = [10, 9, 2, 5, 3, 7, 101, 18] → 4 (2, 3, 7, 18)
nums = [0, 1, 0, 3, 2, 3] → 4
nums = [7, 7, 7] → 1Hints
- O(n²) DP: dp[i] = length of the longest increasing subsequence ending at i = 1 + max(dp[j]) for j < i with nums[j] < nums[i].
- O(n log n): maintain
tails[k]= smallest possible tail of an increasing subsequence of length k+1. tailsis sorted, so binary-search where each number goes.
Approach
O(n²) DP: dp[i] = 1 + max(dp[j] for j < i if nums[j] < nums[i]). The answer is max(dp).
O(n log n): keep tails, where tails[k] is the smallest tail value among all increasing subsequences of length k + 1. For each x, find the first tail ≥ x (binary search). Replace it with x, or append x if it's larger than every tail. A smaller tail can only help future extensions. The length of tails is the answer. (tails itself isn't necessarily a valid subsequence; only its length is meaningful.)
Complexity
Time: O(n log n). Space: O(n).
Python solution
from bisect import bisect_left
def lengthOfLIS(nums):
tails = []
for x in nums:
i = bisect_left(tails, x)
if i == len(tails):
tails.append(x)
else:
tails[i] = x
return len(tails)JavaScript solution
function lengthOfLIS(nums) {
const tails = [];
for (const x of nums) {
let lo = 0, hi = tails.length;
while (lo < hi) { const mid = (lo + hi) >> 1; if (tails[mid] < x) lo = mid + 1; else hi = mid; }
tails[lo] = x;
}
return tails.length;
}