Skills101
← All coding problems

Longest Increasing Subsequence

mediumDynamic Programming+20 XPTime limit 2s

Find the length of the longest strictly increasing subsequence (elements in order, not necessarily adjacent). In 10 9 2 5 3 7 101 18, one is 2 3 7 101 → length 4.

Input:

  • line 1: n
  • line 2: n integers

Output: the length.

Constraints: 1 ≤ n ≤ 10⁵, −10⁹ ≤ a[i] ≤ 10⁹.

Two levels: the O(n²) DP (dp[i] = 1 + max dp[j] over j < i with a[j] < a[i]) passes the small tests. The large tests need O(n log n): keep tails[k] = the smallest possible tail of an increasing subsequence of length k + 1, and place each number with binary search.

Sample input 1

8
10 9 2 5 3 7 101 18

Sample output 1

4

Sample input 2

6
0 1 0 3 2 3

Sample output 2

4

Sample input 3

7
7 7 7 7 7 7 7

Sample output 3

1

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.