problems / 118

Alice's Best AND Pair

medium bit-manipulation greedy 1000 ms · 256 MB

Alice's Best AND Pair

Alice has written n numbers on a whiteboard. Bob, who only ever thinks in binary, challenges her: "Pick two different numbers from the board — the pair whose bitwise AND is as large as possible." Alice could check every pair, but with so many numbers on the board that would take forever, and Bob is waiting.

You are given the n numbers. Choose two of them at distinct positions i and j (i ≠ j) so that a_i AND a_j (bitwise AND) is as large as possible, and print that maximum value.

Input

The first line contains a single integer n (2 ≤ n ≤ 2·10^5), the number of values on the board.

The second line contains n integers a_1, a_2, …, a_n (0 ≤ a_i < 2^30), separated by spaces.

Output

Print a single integer: the maximum value of a_i AND a_j over all pairs of distinct indices i ≠ j.

Notes

In the first example, the board holds 12 (1100 in binary) and 10 (1010). The only pair is (12, 10), whose AND is 1000 = 8.

In the second example, 28 = 11100, 25 = 11001, and 12 = 01100. The pair (28, 25) gives 11100 AND 11001 = 11000 = 24, which beats every other pair.

Example 1

Input

2
12 10

Output

8

Example 2

Input

3
28 25 12

Output

24

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

Hint 1

An AND can only have a bit set if both numbers have it, so a good answer keeps as many high bits as possible. Decide bits from the highest one down, and ask how many numbers must share a set of bits for their AND to contain all of them.

Hint 2

Keep the list of numbers that contain every bit chosen so far. For each lower bit in turn, check whether at least two of those numbers also have it; if so, commit the bit and narrow the list to those numbers. Picking just the two largest values does not work.

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

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