Description
牛客网 2018校招真题 幸运子序列
Solving Ideas
遍历所有元素作为连续子序列最大值和次大值的情况,即遍历所有连续子序列可能的最大值和次大值的组合
Solution
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
/**
* @author wylu
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
String[] strs = br.readLine().split(" ");
int[] v = new int[n];
for (int i = 0; i < n; i++) {
v[i] = Integer.parseInt(strs[i]);
}
int res = 0;
LinkedList<Integer> stack = new LinkedList<>();
//遍历所有元素作为子串最大值和次大值的情况
for (int i = 0; i < n; i++) {
//当前元素作为连续子序列(也即子串)的最大值的情况
while (!stack.isEmpty() && stack.peek() <= v[i]) {
res = Math.max(res, v[i] ^ stack.pop());
}
//当前元素作为连续子序列的次大值的情况
if (!stack.isEmpty()) {
res = Math.max(res, v[i] ^ stack.peek());
}
stack.push(v[i]);
}
System.out.println(res);
}
}