v9.1.1
Menu

Longest Increasing Subsequence

mediumFREEDynamic ProgrammingBlind 75

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

A subsequence is derived from the array by deleting some or no elements without changing the order of the remaining elements.

Example

Input
10,9,2,5,3,7,101,18
Output
4
Reasoning
  • Input: nums is a list of 8 integers, 10, 9, 2, 5, 3, 7, 101, 18. A valid subsequence keeps the original order, may skip elements, and each value beats the previous one.
  • Starting at 1010 or 99 is weak: only 101101 or 1818 follow and are bigger, so those chains stop at length 22.
  • After 22, the values 55 and 33 cannot both be used (55 comes first and 5>35 > 3), so a chain picks one, then reaches 77: 2<5<72 < 5 < 7 or 2<3<72 < 3 < 7.
  • Likewise 101101 and 1818 clash, so each chain ends with one of them: 2<5<7<1012 < 5 < 7 < 101 or 2<3<7<182 < 3 < 7 < 18. All four such chains have length 44.
  • Why not 55? The array splits into decreasing groups (10,9,2)(10, 9, 2), (5,3)(5, 3), (7)(7), (101,18)(101, 18); a chain takes at most one value per group, so 44 is the ceiling.
  • Output: 4, a single integer. Notice that equal values never extend a chain, so an array of five 77s gives 11.

Constraints

  • 1 <= len(nums) <= 2500
  • -10^4 <= nums[i] <= 10^4

More from Blind 75

solution.py

Test results

Sign in to run your code against the test cases.