Longest increasing subsequence
Medium TimeO(n²) SpaceO(n)
A subsequence keeps the original order but may skip elements, and this one has to increase strictly at every step. Given a list, return the length of the longest such run. Its elements need not be adjacent, and an empty array answers 0.
Examples
Example 1
- Input
- nums = [10, 9, 2, 5, 3, 7, 101, 18]
- Output
42, 3, 7, 18increases and is four long;2, 5, 7, 101is another four.
Example 2
- Input
- nums = [5, 4, 3]
- Output
- Nothing increases anywhere, so the longest run is a single element.
1
The Code
function lengthOfLIS(nums) {
const best = new Array(nums.length).fill(1);
let answer = 1;
for (let i = 1; i < nums.length; i++) {
for (let j = 0; j < i; j++) {
if (nums[j] < nums[i] && best[j] + 1 > best[i]) {
best[i] = best[j] + 1;
}
}
if (best[i] > answer) answer = best[i];
}
return answer;
}
lengthOfLIS([10, 9, 2, 5, 3, 7, 101, 18]);Done
The first 18 calls, of 44. This one does not fit on a page.
More like this
All dynamic programming examples (20) →- Climbing stairs Count the ways to the top — Fibonacci in disguise.
- Coin change Try every coin and keep the cheapest way to make the amount.
- Max subarray One pass, two running totals — Kadane’s algorithm.
- LCS Match a character or drop one from either string.
- Edit distance Insert, delete, or replace — take the cheapest at each mismatch.
- 0/1 Knapsack For each item, take it or leave it — keep the more valuable branch.