Approach
Sorting and greedy selection
For Maximum Bitwise and After Increment Operations, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 51 lines of C++ from the credited upstream file maximum-bitwise-and-after-increment-operations.cpp.
- The implementation visibly relies on sequence storage.
- 4 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
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 maximumAND(vector<int>& nums, int k, int m) {8 int result = 0;9 for (int i = bit_width(static_cast<uint32_t>(ranges::max(nums) + k)) - 1; i >= 0; --i) {10 const auto& target = result | (1 << i);11 vector<int> costs;12 costs.reserve(size(nums));13 for (const auto& x : nums) {14 const auto& l = bit_width(static_cast<uint32_t>(target & ~x));15 const auto& mask = (1ll << l) - 1;16 costs.emplace_back((target & mask) - (x & mask));17 }18 ranges::nth_element(costs, begin(costs) + (m - 1));19 if (accumulate(cbegin(costs), cbegin(costs) + m, 0ll) <= k) {20 result |= 1 << i;21 }22 }23 return result;24 }25};26 27282930class Solution2 {31public:32 int maximumAND(vector<int>& nums, int k, int m) {33 int result = 0;34 for (int i = bit_width(static_cast<uint32_t>(ranges::max(nums) + k)) - 1; i >= 0; --i) {35 const auto& target = result | (1 << i);36 vector<int> costs;37 costs.reserve(size(nums));38 for (const auto& x : nums) {39 const auto& l = bit_width(static_cast<uint32_t>(target & ~x));40 const auto& mask = (1ll << l) - 1;41 costs.emplace_back((target & mask) - (x & mask));42 }43 ranges::sort(costs);44 if (accumulate(cbegin(costs), cbegin(costs) + m, 0ll) <= k) {45 result |= 1 << i;46 }47 }48 return result;49 }50};51