iq.lab
Python starts when a code cell comes near or you run one
mediumDynamic programming, 1D target 25 min

Longest increasing subsequence

You get a list of integers nums. A subsequence keeps some of the items in their original order and drops the rest; the kept items do not have to be neighbors.

Return the length of the longest subsequence that is strictly increasing: every item is bigger than the one before it. Equal items do not count as increasing.

Example 1
Inputnums = [5, 2, 8, 6, 3, 6, 9, 7]Output4

One longest is 2, 3, 6, 9, from positions 1, 4, 5 and 6. Another is 2, 3, 6, 7. None has 5 items.

Example 2
Inputnums = [4, 4, 4]Output1

Equal items are not increasing, so the best is a single item.

Example 3
Inputnums = [1, 5, 2, 3]Output3

1, 2, 3 skips the 5. The longest rising stretch of neighbors, [1, 5] or [2, 3], has only 2 items.

Constraints
  • 1 ≤ len(nums) ≤ 2,500

  • -104 ≤ nums[i] ≤ 104

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.