You are given a 0-indexed integer array nums and an integer k.
In one operation, you can pick any index i of nums such that 0 <= i < nums.length - 1 and replace nums[i] and nums[i + 1] with a single occurrence of nums[i] & nums[i + 1], where & represents the bitwise AND operator.
Return _theminimum possible value of the bitwise _ORof the remaining elements ofnumsafter applyingat mostkoperations.
The goal is to minimize the OR of the array after up to k operations, where each operation merges two adjacent elements using AND. Since AND can only reduce bits, and OR accumulates bits, we want to merge elements that have overlapping bits set, especially those contributing most to the OR. Greedily merging the pairs with the most overlap can help minimize the final OR.
classSolution {
public:int minimizeOR(vector<int>& nums, int k) {
function<int(vector<int>, int)> dfs = [&](vector<int> arr, int rem) {
if (rem ==0|| arr.size() ==1) {
int ans =0;
for (int x : arr) ans |= x;
return ans;
}
int res = INT_MAX;
for (int i =0; i < arr.size() -1; ++i) {
vector<int> nxt = arr;
nxt[i] = arr[i] & arr[i+1];
nxt.erase(nxt.begin() + i +1);
res = min(res, dfs(nxt, rem -1));
}
return res;
};
returndfs(nums, k);
}
};
classSolution {
publicintminimizeOR(int[] nums, int k) {
return dfs(nums, k);
}
privateintdfs(int[] arr, int rem) {
if (rem == 0 || arr.length== 1) {
int ans = 0;
for (int x : arr) ans |= x;
return ans;
}
int res = Integer.MAX_VALUE;
for (int i = 0; i < arr.length- 1; ++i) {
int[] nxt =newint[arr.length- 1];
for (int j = 0, idx = 0; j < arr.length; ++j) {
if (j == i) nxt[idx++]= arr[i]& arr[i+1];
elseif (j != i+1) nxt[idx++]= arr[j];
}
res = Math.min(res, dfs(nxt, rem - 1));
}
return res;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funminimizeOR(nums: IntArray, k: Int): Int {
fundfs(arr: List<Int>, rem: Int): Int {
if (rem ==0|| arr.size ==1) return arr.reduce { a, b -> a or b }
var res = Int.MAX_VALUE
for (i in0 until arr.size - 1) {
val nxt = arr.toMutableList()
nxt[i] = arr[i] and arr[i+1]
nxt.removeAt(i+1)
res = minOf(res, dfs(nxt, rem - 1))
}
return res
}
return dfs(nums.toList(), k)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
defminimizeOR(nums: list[int], k: int) -> int:
defdfs(arr: list[int], rem: int) -> int:
if rem ==0or len(arr) ==1:
ans =0for x in arr:
ans |= x
return ans
res =2**31-1for i in range(len(arr)-1):
nxt = arr[:]
nxt[i] = arr[i] & arr[i+1]
nxt.pop(i+1)
res = min(res, dfs(nxt, rem-1))
return res
return dfs(nums, k)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
impl Solution {
pubfnminimize_or(nums: Vec<i32>, k: i32) -> i32 {
fndfs(arr: Vec<i32>, rem: i32) -> i32 {
if rem ==0|| arr.len() ==1 {
arr.iter().fold(0, |acc, &x| acc | x)
} else {
letmut res =i32::MAX;
for i in0..arr.len()-1 {
letmut nxt = arr.clone();
nxt[i] = arr[i] & arr[i+1];
nxt.remove(i+1);
res = res.min(dfs(nxt, rem-1));
}
res
}
}
dfs(nums, k)
}
}