Greedy | Java
\nDue to problem constraints, the best strategy is to select a single number from the array and shift it by K. To achieve this efficiently, we should precompute
\nDue to problem constraints, **the best strategy is to select a single number from the array and shift it by K.** To achieve this efficiently, we should precompute the array\'s results without any shifts. For each element, we subtract it from the precomputed result and apply a K-shift using the bitwise OR operation to update the result. However, one issue arises since the bitwise OR operation is a destructive operation, and we cannot reverse it for a single number. Therefore, we need to manually perform bit counting by utilizing the update method.\n\n```\nclass Solution {\n    void update(int[] bits, int n, int op) {\n        for (int i = 0; i < bits.length; ++i) {\n            if ((n & (1 L << i)) != 0) {\n                bits[i] += op;\n            }\n        }\n    }\n\n    int toInt(int[] bits) {\n        int r = 0;\n        for (int i = 0; i < bits.length; ++i) {\n            if (bits[i] > 0) {\n                r |= 1 << i;\n            }\n        }\n        return r;\n    }\n\n    public long maximumOr(int[] nums, int k) {\n        int[] bits = new int[32];\n        for (int n: nums) {\n            update(bits, n, 1);\n        }\n        long r = toInt(bits);\n        for (int n: nums) {\n            update(bits, n, -1);\n            long m = toInt(bits);\n            m |= (long) n << k;\n            r = Math.max(r, m);\n            update(bits, n, 1);\n        }\n        return r;\n    }\n}\n```
[]