-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFindMaximumSubsetXOROfGivenSet.java
More file actions
85 lines (69 loc) · 1.79 KB
/
FindMaximumSubsetXOROfGivenSet.java
File metadata and controls
85 lines (69 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package ProblemWithSolutions;
public class FindMaximumSubsetXOROfGivenSet {
static final int INT_BITS = 32;
public static void main(String[] args) {
int set[] = { 1, 2, 3 };
int n = set.length;
System.out.print("Max subset XOR is ");
System.out.print(maxSubarrayXOR(set, n));
}
static int maxSubarrayXOR(int set[], int n) {
// Initialize index of
// chosen elements
int index = 0;
// Traverse through all
// bits of integer
// starting from the most
// significant bit (MSB)
for (int i = INT_BITS - 1; i >= 0; i--) {
// Initialize index of
// maximum element and
// the maximum element
int maxInd = index;
int maxEle = Integer.MIN_VALUE;
for (int j = index; j < n; j++) {
// If i'th bit of set[j]
// is set and set[j] is
// greater than max so far.
if ((set[j] & (1 << i)) != 0 && set[j] > maxEle) {
maxEle = set[j];
maxInd = j;
}
}
// If there was no
// element with i'th
// bit set, move to
// smaller i
if (maxEle == -2147483648)
continue;
// Put maximum element
// with i'th bit set
// at index 'index'
int temp = set[index];
set[index] = set[maxInd];
set[maxInd] = temp;
// Update maxInd and
// increment index
maxInd = index;
// Do XOR of set[maxIndex]
// with all numbers having
// i'th bit as set.
for (int j = 0; j < n; j++) {
// XOR set[maxInd] those
// numbers which have the
// i'th bit set
if (j != maxInd && (set[j] & (1 << i)) != 0)
set[j] = set[j] ^ set[maxInd];
}
// Increment index of
// chosen elements
index++;
}
// Final result is
// XOR of all elements
int res = 0;
for (int i = 0; i < n; i++)
res ^= set[i];
return res;
}
}