Longest Increasing Subsequence

Medium1-D dynamic programming

Given an array of integers nums, return the length of its longest strictly increasing subsequence.

A subsequence keeps some of the values in their original order, not necessarily next to each other. Strictly increasing means each value is larger than the one before it, so equal values cannot both be used.

Examples

Example 1
Input:  nums = [5, 1, 6, 2, 3, 9]
Output: 4

1, 2, 3, 9. The values do not have to be next to each other.

Example 2
Input:  nums = [4, 4, 4]
Output: 1

Equal values do not count as increasing.

Constraints

  • 1 ≤ nums.length ≤ 2500
  • -10⁴ ≤ nums[i] ≤ 10⁴

Stuck?

Hint 1

Let best[i] be the longest increasing subsequence that ends at nums[i]. It extends the best one ending at some earlier, smaller value.

Hint 2

For each i, look at every j < i with nums[j] < nums[i] and take best[j] + 1. That is O(n²); keeping the smallest possible tail for each length and binary searching it makes it O(n log n).

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 10 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur