• + 1 comment

    O(n), 3 pass over the array A. there are only linearly many pairs (M1, M2)

    int andXorOr(int N, const vector<int>& A) {
        int maxXOR = 0;
        vector<int> prevSmaller(N, -1), nextSmaller(N, N);
        stack<int> prev, next;
        prev.push(0);
        next.push(N - 1);
        for (int i = 1; i < N; i++) {
            while (!prev.empty() and A[prev.top()] >= A[i]) prev.pop();
            if (!prev.empty()) prevSmaller[i] = prev.top();
            prev.push(i);
        }
        for (int i = N - 2; i >= 0; i--) {
            while (!next.empty() and A[i] <= A[next.top()]) next.pop();
            if (!next.empty()) nextSmaller[i] = next.top();
            next.push(i);
        }
        for (int i = 0; i < N; i++) {
            if (prevSmaller[i] != -1) maxXOR = max(maxXOR, A[i] ^ A[prevSmaller[i]]);
            if (nextSmaller[i] != N) maxXOR = max(maxXOR, A[i] ^ A[nextSmaller[i]]);
        }
        return maxXOR;
    }