You are given an array nums and an integer k. You need to find a subarray of nums such that the absolute difference between k and the bitwise
OR of the subarray elements is assmall as possible. In other words, select a subarray nums[l..r] such that |k - (nums[l] OR nums[l + 1] ... OR nums[r])| is minimum.
Return the minimum possible value of the absolute difference.
A subarray is a contiguous non-empty sequence of elements within an array.
Input: nums =[1,2,4,5], k =3Output: 0Explanation:
The subarray `nums[0..1]` has `OR` value 3, which gives the minimum absolute
difference `|3 - 3| = 0`.
Input: nums =[1,3,1,3], k =2Output: 1Explanation:
The subarray `nums[1..1]` has `OR` value 3, which gives the minimum absolute
difference `|3 - 2| = 1`.
For each subarray, the bitwise OR can only increase or stay the same as we extend the subarray. We can use a set to keep all possible ORs ending at each position, and for each, check the absolute difference to k.
Initialize a set to keep all possible ORs ending at the previous position.
For each number in nums, create a new set of ORs by OR-ing the current number with all ORs from the previous set, and also include the current number itself.
For each OR value, update the minimum absolute difference to k.
classSolution {
public:int closestToK(vector<int>& nums, int k) {
int ans = INT_MAX;
unordered_set<int> prev;
for (int x : nums) {
unordered_set<int> cur = {x};
for (int v : prev) cur.insert(v | x);
for (int v : cur) ans = min(ans, abs(v - k));
prev = cur;
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
funcclosestToK(nums []int, kint) int {
ans:=1<<31-1prev:=map[int]struct{}{}
for_, x:=rangenums {
cur:=map[int]struct{}{x: {}}
forv:=rangeprev {
cur[v|x] = struct{}{}
}
forv:=rangecur {
ifabs(v-k) < ans {
ans = abs(v-k)
}
}
prev = cur }
returnans}
funcabs(xint) int { ifx < 0 { return-x }; returnx }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
publicintclosestToK(int[] nums, int k) {
int ans = Integer.MAX_VALUE;
Set<Integer> prev =new HashSet<>();
for (int x : nums) {
Set<Integer> cur =new HashSet<>();
cur.add(x);
for (int v : prev) cur.add(v | x);
for (int v : cur) ans = Math.min(ans, Math.abs(v - k));
prev = cur;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution {
funclosestToK(nums: IntArray, k: Int): Int {
var ans = Int.MAX_VALUE
var prev = mutableSetOf<Int>()
for (x in nums) {
val cur = mutableSetOf(x)
for (v in prev) cur.add(v or x)
for (v in cur) ans = minOf(ans, kotlin.math.abs(v - k))
prev = cur
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defclosestToK(self, nums: list[int], k: int) -> int:
ans = float('inf')
prev = set()
for x in nums:
cur = {x}
for v in prev:
cur.add(v | x)
for v in cur:
ans = min(ans, abs(v - k))
prev = cur
return ans