classSolution: defmaximumOr(self, nums: List[int], k: int) -> int: n = len(nums) suf = [0] * (n + 1) for i inrange(n - 1, 0, -1): suf[i] = suf[i + 1] | nums[i] ans = pre = 0 for i, x inenumerate(nums): ans = max(ans, pre | (x << k) | suf[i + 1]) pre |= x return ans
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14
classSolution { publiclongmaximumOr(int[] nums, int k) { intn= nums.length; varsuf=newint[n + 1]; for (inti= n - 1; i > 0; i--) suf[i] = suf[i + 1] | nums[i]; longans=0; for (inti=0, pre = 0; i < n; i++) { ans = Math.max(ans, pre | ((long) nums[i] << k) | suf[i + 1]); pre |= nums[i]; } return ans; } }
[sol1-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: longlongmaximumOr(vector<int> &nums, int k){ int n = nums.size(), suf[n + 1]; suf[n] = 0; for (int i = n - 1; i; i--) suf[i] = suf[i + 1] | nums[i]; longlong ans = 0; for (int i = 0, pre = 0; i < n; i++) { ans = max(ans, pre | ((longlong) nums[i] << k) | suf[i + 1]); pre |= nums[i]; } return ans; } };
[sol1-Go]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
funcmaximumOr(nums []int, k int)int64 { n := len(nums) suf := make([]int, n+1) for i := n - 1; i > 0; i-- { suf[i] = suf[i+1] | nums[i] } ans, pre := 0, 0 for i, x := range nums { ans = max(ans, pre|x<<k|suf[i+1]) pre |= x } returnint64(ans) }
funcmax(a, b int)int { if a < b { return b }; return a }