All problems

Problem 185

Longest Increasing Subsequence

Medium · 20 pts · Array, Dynamic Programming, Binary Search

Problem

You are given an array of N integers. A subsequence is obtained by deleting some elements (possibly none) without changing the order of the rest; the chosen elements do not need to be next to each other. Find the length of the longest subsequence that is strictly increasing. The O(N²) dynamic programming solution is too slow for N = 100,000. Use the patience sorting method instead: keep an array tails, where tails[k] is the smallest possible last value of an increasing subsequence of length k + 1. For each element, binary search for the first tail that is >= it and replace it (or append it). The length of tails is the answer.

Input

First line: integer N. Second line: N space-separated integers.

Output

Print the length of the LIS.

Constraints

1 <= N <= 100000; -1000000000 <= A[i] <= 1000000000

Example input

8
10 9 2 5 3 7 101 18

Example output

4

Explanation

In 10 9 2 5 3 7 101 18, the subsequence 2 3 7 101 (or 2 5 7 18) is strictly increasing and has length 4. No increasing subsequence of length 5 exists.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Coin Change Ways Next: Longest Common Subsequence