|
38 | 38 |
|
39 | 39 | ## Solutions
|
40 | 40 |
|
| 41 | +**Solution 1: Greedy + Preprocessing** |
| 42 | + |
| 43 | +We notice that in order to maximize the answer, we should apply $k$ times of bitwise OR to the same number. |
| 44 | + |
| 45 | +First, we preprocess the suffix OR value array $suf$ of the array $nums,ドル where $suf[i]$ represents the bitwise OR value of $nums[i], nums[i + 1], \cdots, nums[n - 1]$. |
| 46 | + |
| 47 | +Next, we traverse the array $nums$ from left to right, and maintain the current prefix OR value $pre$. For the current position $i,ドル we perform $k$ times of bitwise left shift on $nums[i],ドル i.e., $nums[i] \times 2^k,ドル and perform bitwise OR operation with $pre$ to obtain the intermediate result. Then, we perform bitwise OR operation with $suf[i + 1]$ to obtain the maximum OR value with $nums[i]$ as the last number. By enumerating all possible positions $i,ドル we can obtain the final answer. |
| 48 | + |
| 49 | +The time complexity is $O(n),ドル and the space complexity is $O(n)$. Here, $n$ is the length of the array $nums$. |
| 50 | + |
41 | 51 | <!-- tabs:start -->
|
42 | 52 |
|
43 | 53 | ### **Python3**
|
@@ -123,6 +133,49 @@ func max(a, b int) int {
|
123 | 133 | }
|
124 | 134 | ```
|
125 | 135 |
|
| 136 | +### **TypeScript** |
| 137 | + |
| 138 | +```ts |
| 139 | +function maximumOr(nums: number[], k: number): number { |
| 140 | + const n = nums.length; |
| 141 | + const suf: bigint[] = Array(n + 1).fill(0n); |
| 142 | + for (let i = n - 1; i >= 0; i--) { |
| 143 | + suf[i] = suf[i + 1] | BigInt(nums[i]); |
| 144 | + } |
| 145 | + let [ans, pre] = [0, 0n]; |
| 146 | + for (let i = 0; i < n; i++) { |
| 147 | + ans = Math.max(Number(ans), Number(pre | (BigInt(nums[i]) << BigInt(k)) | suf[i + 1])); |
| 148 | + pre |= BigInt(nums[i]); |
| 149 | + } |
| 150 | + return ans; |
| 151 | +} |
| 152 | +``` |
| 153 | + |
| 154 | +### **Rust** |
| 155 | + |
| 156 | +```rust |
| 157 | +impl Solution { |
| 158 | + pub fn maximum_or(nums: Vec<i32>, k: i32) -> i64 { |
| 159 | + let n = nums.len(); |
| 160 | + let mut suf = vec![0; n + 1]; |
| 161 | + |
| 162 | + for i in (0..n).rev() { |
| 163 | + suf[i] = suf[i + 1] | nums[i] as i64; |
| 164 | + } |
| 165 | + |
| 166 | + let mut ans = 0i64; |
| 167 | + let mut pre = 0i64; |
| 168 | + let k64 = k as i64; |
| 169 | + for i in 0..n { |
| 170 | + ans = ans.max(pre | ((nums[i] as i64) << k64) | suf[i + 1]); |
| 171 | + pre |= nums[i] as i64; |
| 172 | + } |
| 173 | + |
| 174 | + ans |
| 175 | + } |
| 176 | +} |
| 177 | +``` |
| 178 | + |
126 | 179 | ### **...**
|
127 | 180 |
|
128 | 181 | ```
|
|
0 commit comments