Suppose you have an integer sequence, we define a lucky number as a special integer which is the XOR value of the sequence’s greatest and strict second greatest element. For example, in [1,2,3,3], 3 is the greatest element and 2 is the strict second greatest one, even though we have two 3 at the same time; so the lucky number is 2 xor 3 = 1.
Now given an N-length integer sequence, please find out the maximum lucky number of all continuous subsequences.
输入描述:
The first line is an integer n, representing the length of the value of V[i](1 <= V[i] <= 10^8) in the sequence respectively. We’ll ensure that there are at least two different values from V[1] to V[n. Define the continuous subsequence as [V[1],V[l+1],V[l+2], … ,V[r]] ( 1 <= l <= r <= n)
30% small input: 2 <= n <= 10
40% medium input: 2 <= n <= 5000
30% large input: 2 <= n <= 100000
输出描述:
Output the greatest lucky number
示例1:
输入
5
5 2 1 4 3
输出
7
python代码
array_length = raw_input()
array = raw_input()
num = [int(n) for n in array.split()]
q = []
ans = -999
for value in num:
while q and q[-1] <= value:#最大的情况
ans = max(ans,q[-1]^value)
q.pop()
if q:#次大的情况
ans = max(ans,q[-1]^value)
q.append(value)
print ans
c++代码
#include<iostream>
#include<stdio.h>
#include<deque>
using namespace std;
deque<int>q;
int main(){
int i, x, ans = -999,n;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
scanf("%d",&x);
while(!q.empty()&&q.back()<=x)
{
ans = max(ans,q.back()^x);
q.pop_back();
}
if(q.size()>1) ans= max(ans,q.back()^x);
q.push_back(x);
}
printf("%d",ans);
}