All problems

Problem 33

Longest Consecutive Sequence

Medium · 20 pts · Array, Hash Table

Problem

You are given an unsorted array of N integers. Find the length of the longest run of consecutive integers, such as 4, 5, 6, 7, where every value of the run appears somewhere in the array. The order of the elements in the array does not matter, and duplicates count once. Put all values in a hash set. A value x starts a run only if x - 1 is not in the set; from each such start, count upward while x + 1, x + 2, ... are present. Each value is visited a constant number of times, so this is O(N).

Input

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

Output

Print the length of the longest consecutive sequence.

Constraints

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

Example input

6
100 4 200 1 3 2

Example output

4

Explanation

The array is 100 4 200 1 3 2. The values 1, 2, 3 and 4 all appear and form a run of length 4, while 100 and 200 are runs of length 1. So the answer is 4.

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

Previous: Maximum Product Subarray Next: Subarray Sum Equals K