- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- Move the appropriate boundary after each midpoint check and return the final feasible position.
Code notes
- 94 lines of C++ from the credited upstream file find-subarray-with-bitwise-or-closest-to-k.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 8 loop blocks detected.
Complexity
Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int minimumDifference(vector<int>& nums, int k) {8 BitCount count(bit_length(ranges::max(nums)));9 int result = numeric_limits<int>::max();10 for (int left = 0, right = 0; right < size(nums); ++right) {11 count += nums[right];12 while (left <= right) {13 const auto& f = count.bitOr();14 result = min(result, abs(f - k));15 if (f <= k) {16 break;17 }18 count -= nums[left++];19 }20 }21 return result;22 }23 24private:25 int bit_length(int x) {26 return (x ? std::__lg(x) : -1) + 1;27 }28 29 class BitCount {30 public:31 BitCount(int n)32 : l_(0)33 , n_(n)34 , count_(n) {35 36 }37 38 int bitOr() const {39 int num = 0;40 for (int i = 0; i < n_; ++i) {41 if (count_[i]) {42 num |= 1 << i;43 }44 }45 return num;46 }47 48 void operator+=(int num) {49 ++l_;50 for (int i = 0; i < n_; ++i) {51 if (num & (1 << i)) {52 ++count_[i];53 }54 }55 }56 57 void operator-=(int num) {58 --l_;59 for (int i = 0; i < n_; ++i) {60 if (num & (1 << i)) {61 --count_[i];62 }63 }64 }65 66 private:67 int l_;68 int n_;69 vector<int> count_;70 };71};72 73747576class Solution2 {77public:78 int minimumDifference(vector<int>& nums, int k) {79 int result = numeric_limits<int>::max();80 unordered_set<int> dp; 81 for (const auto& x : nums) {82 unordered_set<int> new_dp = {x};83 for (const auto& f: dp) {84 new_dp.emplace(f | x);85 }86 for (const auto& f : new_dp) {87 result = min(result, abs(f - k));88 }89 dp = move(new_dp);90 }91 return result;92 }93};94