3171. Find Subarray With Bitwise OR Closest to K Hard
1/**
2 * [3171] Find Subarray With Bitwise OR Closest to K
3 *
4 * You are given an array nums and an integer k. You need to find a <span data-keyword="subarray-nonempty">subarray</span> of nums such that the absolute difference between k and the bitwise OR of the subarray elements is as small 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.
5 * Return the minimum possible value of the absolute difference.
6 * A subarray is a contiguous non-empty sequence of elements within an array.
7 *
8 * <strong class="example">Example 1:
9 * <div class="example-block">
10 * Input: <span class="example-io">nums = [1,2,4,5], k = 3</span>
11 * Output: 0
12 * Explanation:
13 * The subarray nums[0..1] has OR value 3, which gives the minimum absolute difference |3 - 3| = 0.
14 * </div>
15 * <strong class="example">Example 2:
16 * <div class="example-block">
17 * Input: <span class="example-io">nums = [1,3,1,3], k = 2</span>
18 * Output: 1
19 * Explanation:
20 * The subarray nums[1..1] has OR value 3, which gives the minimum absolute difference |3 - 2| = 1.
21 * </div>
22 * <strong class="example">Example 3:
23 * <div class="example-block">
24 * Input: <span class="example-io">nums = [1], k = 10</span>
25 * Output: <span class="example-io">9</span>
26 * Explanation:
27 * There is a single subarray with OR value 1, which gives the minimum absolute difference |10 - 1| = 9.
28 * </div>
29 *
30 * Constraints:
31 *
32 * 1 <= nums.length <= 10^5
33 * 1 <= nums[i] <= 10^9
34 * 1 <= k <= 10^9
35 *
36 */
37pub struct Solution {}
38
39// problem: https://leetcode.com/problems/find-subarray-with-bitwise-or-closest-to-k/
40// discuss: https://leetcode.com/problems/find-subarray-with-bitwise-or-closest-to-k/discuss/?currentPage=1&orderBy=most_votes&query=
41
42// submission codes start here
43
44impl Solution {
45 pub fn minimum_difference(nums: Vec<i32>, k: i32) -> i32 {
46 0
47 }
48}
49
50// submission codes end
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55
56 #[test]
57 fn test_3171() {
58 }
59}
60
Back
© 2025 bowen.ge All Rights Reserved.