Longest Increasing Subsequence

medium dp binary-search 1000 ms · 256 MB

Longest Increasing Subsequence

Given an array of n integers, find the length of its longest strictly increasing subsequence.

A subsequence is obtained by deleting zero or more elements without changing the order of the rest.

Input

The first line contains n (1 ≤ n ≤ 2·10^5).

The second line contains n integers a_1, …, a_n (-10^9 ≤ a_i ≤ 10^9).

Output

Print the length of the longest strictly increasing subsequence.

Example 1

Input

8
10 9 2 5 3 7 101 18

Output

4

Example 2

Input

5
7 7 7 7 7

Output

1

Hints · reveal one at a time if you're stuck

Hint 1

The classic dynamic programme over pairs of positions is correct but too slow for n = 2·10^5. Instead of remembering every subsequence, what is the most useful single value to keep for each possible length?

Hint 2

For each length k, keep the smallest possible last value of a strictly increasing subsequence of length k. Those stored values stay in sorted order, so when a new value arrives, you only need to find where it fits.

Hint 3

Use binary search on the stored values to find the position for the new value, and either replace that value or extend the list. Whether equal values may replace or extend it depends on whether you search for the first value not less than x or the first value greater than x.

report an issue Prefer your own editor? sooks prep 4 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.