public static int getMaxEOR1(int[] arr){
int max = Integer.MIN_VALUE;
for (int i = 0 ; i < arr.length ;i++){
for (int start = 0 ;start <= i;start++) {
int res = 0;
for (int j = start; j <= i; j++) {
res ^= arr[j];
}
max = Math.max(max, res);
}
}
return max;
}
public static int getMaxEOR2(int[] arr){
int max = Integer.MIN_VALUE;
int[] dp = new int[arr.length];
int eor = 0;
for (int i = 0 ; i < arr.length; i++){
eor ^= arr[i]; // 0 .. i 的异或和
max = Math.max(max,eor); // 由于下面的start的初始为1 没有包括0 ,
// 所以这里需要将0..i的包括进来
for (int start = 1 ; start <= i ;start++){
//求的是start .. i 的异或和 ,start = 1 .. i
int curROR = eor ^ dp[start - 1];
max = Math.max(max,curROR);
}
dp[i] = eor;
}
return max;
}
前缀树的解法
public static class Node {
public Node[] nexts = new Node[2];
}
public static class NumTrie {
public Node head = new Node();
public void add(int num) {
Node cur = head;
for (int move = 31; move >= 0; move--) {
int path = ((num >> move) & 1);
cur.nexts[path] = cur.nexts[path] == null ? new Node() : cur.nexts[path];
cur = cur.nexts[path];
}
}
public int maxXor(int num) {
Node cur = head;
int res = 0;
for (int move = 31; move >= 0; move--) {
int path = (num >> move) & 1;
int best = move == 31 ? path : (path ^ 1);
best = cur.nexts[best] != null ? best : (best ^ 1);
res |= (path ^ best) << move;
cur = cur.nexts[best];
}
return res;
}
}
public static int maxXorSubarray(int[] arr) {
if (arr == null || arr.length == 0) {
return 0;
}
int max = Integer.MIN_VALUE;
int eor = 0;
NumTrie numTrie = new NumTrie();
numTrie.add(0);
for (int i = 0; i < arr.length; i++) {
eor ^= arr[i];
max = Math.max(max, numTrie.maxXor(eor));
numTrie.add(eor);
}
return max;
}
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有