Maximum Subset Gain Under an OR Threshold

Medium · Coding & Algorithms · Software Engineer · Online Assessment

Problem Statement

You are given two equal-length integer lists profits and masks, together with a non-negative integer limit. Index i represents an item worth profits[i] whose selection activates the binary flags in masks[i].

Pick any subset of indices (including the empty subset) so that combining the masks values of all chosen items with the bitwise OR operator (|) produces a result less than or equal to limit. An empty selection has a combined bitwise OR of 0 and a total gain of 0.

Return the largest possible sum of profits[i] across any valid subset.

def max_profit_bitwise_or(profits: List[int], masks: List[int], limit: int) -> int:

Examples

Example 1

Input: profits = [8, 12, 9, 14], masks = [4, 2, 1, 7], limit = 6
Output: 21

Explanation: - Item 3 (mask = 7) already exceeds limit = 6 on its own and cannot be picked. - Taking items 0, 1, and 2 together gives 4 | 2 | 1 = 7 > 6, which violates the ceiling. - Pairing items 0 and 1 gives 4 | 2 = 6 <= 6 with total gain 8 + 12 = 20. - Pairing items 1 and 2 gives 2 | 1 = 3 <= 6 with total gain 12 + 9 = 21, which is optimal.

Example 2

Input: profits = [15, 25, 30], masks = [16, 9, 12], limit = 6
Output: 0

Explanation: Every item has a bitmask strictly above 6, and bitwise OR can never clear set bits. Choosing zero items yields bitwise OR 0 <= 6 and total gain 0.

Constraints

  • 1 <= len(profits) <= 10^5
  • len(profits) == len(masks)
  • 1 <= profits[i] <= 10^9
  • 0 <= masks[i] <= 10^9
  • 0 <= limit <= 10^9

Step-by-step walkthrough

  1. Understand the goal and why simple greedy fails

    Each item i contributes a positive value profits[i] >= 1 and carries an integer bitmask masks[i]. We want to pick any subset of items whose combined bitwise OR (the operation | that sets a bit position to 1 whenever at least one chosen item has a 1 there) stays <= limit, maximizing the sum of profits[i]. Selecting no items at all produces bitwise OR 0 and total profit 0.

    • Input: profits and masks of length n <= 10^5, plus 0 <= limit <= 10^9 (at most 30 binary bits).
    • Output: maximum total profit (an integer >= 0).

    Testing all 2^n subsets works only for tiny n. Meanwhile, greedily taking every item with masks[i] <= limit fails because bitwise OR can merge smaller masks into a larger number that crosses limit:

    item 0: mask = 4 (binary 100) <= 6
    item 1: mask = 2 (binary 010) <= 6
    item 2: mask = 1 (binary 001) <= 6
    all three together: 4 | 2 | 1 = 7 (binary 111) > 6   <- invalid!
    

    The tension is that | operates bit by bit, whereas <= limit compares whole integers. We need a clean bridge between the two.

  2. Turn a numeric ceiling into a submask rule

    Call mask a submask of cap when every 1-bit of mask is also a 1-bit of cap. In binary, mask never turns on a bit that cap leaves 0, which we test in O(1) time with (mask & cap) == mask:

    cap  = 6 (binary 110)
    mask = 4 (binary 100) -> (100 & 110) = 100 == mask  (submask!)
    mask = 1 (binary 001) -> (001 & 110) = 000 != mask  (NOT a submask, even though 1 <= 6)
    

    Suppose we fix any integer cap <= limit as our allowed set of 1-bits and greedily include every item whose mask is a submask of cap:

    1. Always valid: Because no chosen item turns on a bit outside cap, their combined bitwise OR also stays inside cap, guaranteeing combined_or <= cap <= limit.
    2. Optimal for that cap: Every profits[i] is positive, and adding more submask items can never violate cap, so taking all submask items beats taking only part of them.

    Conversely, if an optimal subset has combined OR equal to some integer V <= limit, every item in that subset is automatically a submask of V. So maximizing over all cap in 0 .. limit gives the exact answer! The only catch is that limit can reach 10^9—far too many caps to scan one by one.

  3. Shrink a billion caps down to at most 31

    Consider any valid OR outcome V <= limit and compare its binary digits against limit from most significant bit down to bit 0:

    • Case 1 (V == limit): V is a submask of cap = limit.
    • Case 2 (V < limit): Inspect the highest bit position bit where V and limit differ. Because V < limit and both numbers agree on every higher bit, limit must have a 1 at bit while V has a 0 at bit. Below bit, V can contain any mix of 0s and 1s.

    Therefore, V is guaranteed to be a submask of the integer formed by keeping limit's prefix above bit, placing 0 at bit, and filling every bit below bit with 1:

    bit index:    5  4  3  2  1  0
    limit = 45:   1  0  1  1  0  1
                        ^
                        suppose V first drops below limit at bit = 3
    cap (bit 3):  1  0  0  1  1  1   = 39
                  |<-same->|0|<-all 1s->|
    

    Two properties make this family of caps exact:

    1. cap < limit always holds because they match above bit and cap has 0 where limit has 1 at bit (even all 1s below bit sum to (1 << bit) - 1 < (1 << bit)).
    2. Every V that first diverges below limit at bit has zero 1-bits outside cap, so V is a submask of cap.

    We construct just one cap per 1-bit of limit, plus limit itself. Because limit <= 10^9 < 2^30, limit has at most 30 bits, leaving at most 31 candidate caps!

  4. Build the candidate caps in Python

    For each bit index bit in 0 .. limit.bit_length() - 1 where limit has a 1-bit:

    • upper_prefix = (limit >> (bit + 1)) << (bit + 1) clears bit and every lower position while keeping higher bits intact.
    • all_lower_ones = (1 << bit) - 1 sets positions 0 .. bit - 1 to 1.
    • upper_prefix | all_lower_ones combines both parts into cap.

    Here is how that works on limit = 6 (binary 110, bit_length() = 3):

    start:   candidate_caps = [6]                     (binary 110)
    bit = 0: 0-bit, skip
    bit = 1: 1-bit! upper_prefix = 100, lower = 001 -> append 5 (binary 101)
    bit = 2: 1-bit! upper_prefix = 000, lower = 011 -> append 3 (binary 011)
    result:  [6, 5, 3]
    

    (When limit == 0, 0.bit_length() is 0, the loop runs zero times, and candidate_caps is [0]—only items with mask == 0 qualify.)

    def build_candidate_caps(limit: int) -> List[int]:
        """Return ~31 bitmask caps M <= limit that together cover every integer V <= limit."""
        # candidate_caps: list of integer bitmasks <= limit, e.g. [6, 5, 3] for limit = 6 (binary 110).
        # Include limit itself first to cover subsets whose combined bitwise OR equals limit exactly.
        candidate_caps = [limit]
    
        # For each 1-bit of limit, build a cap that matches limit above `bit`, clears `bit` to 0
        # (which guarantees cap < limit), and sets every bit below `bit` to 1 (allowing any lower bits).
        for bit in range(limit.bit_length()):
            is_bit_set = (limit >> bit) & 1
            if is_bit_set == 1:
                upper_prefix = (limit >> (bit + 1)) << (bit + 1)
                all_lower_ones = (1 << bit) - 1
                cap = upper_prefix | all_lower_ones
                candidate_caps.append(cap)
    
        return candidate_caps
    
  5. Sum matching items for each cap

    For each cap returned by build_candidate_caps(limit), scan all n items once and add profit whenever (mask & cap) == mask. Track the highest sum across all caps, initializing best_profit = 0 for the empty subset.

    def max_profit_bitwise_or(profits: List[int], masks: List[int], limit: int) -> int:
        # Phase 1: Generate the O(log(limit)) candidate upper-bound bitmasks (at most 31 for limit <= 10^9).
        caps = build_candidate_caps(limit)
    
        # best_profit starts at 0 because choosing the empty subset (OR = 0, profit = 0) is always valid.
        best_profit = 0
    
        # Phase 2: For each cap, greedily sum EVERY item whose mask only uses 1-bits allowed by `cap`.
        for cap in caps:
            cap_profit = 0
            for profit, mask in zip(profits, masks):
                # Why (mask & cap) == mask instead of mask <= cap:
                # Every 1-bit of `mask` must also be a 1-bit of `cap` (submask test) so that
                # combining all matching items with bitwise OR can never turn on a bit outside `cap`.
                if (mask & cap) == mask:
                    cap_profit += profit
    
            if cap_profit > best_profit:
                best_profit = cap_profit
    
        return best_profit
    
  6. Trace Examples 1 and 2 step by step

    Let's trace Example 1 with profits = [8, 12, 9, 14], masks = [4, 2, 1, 7], and limit = 6 (binary 110):

    Items:
      i = 0: mask = 4 (100), profit = 8
      i = 1: mask = 2 (010), profit = 12
      i = 2: mask = 1 (001), profit = 9
      i = 3: mask = 7 (111), profit = 14
    
    Candidate caps from limit = 6 (110):
      cap = 6 (110): submasks are i=0 (100) and i=1 (010) -> OR = 6 <= 6, profit = 8 + 12 = 20
      cap = 5 (101): submasks are i=0 (100) and i=2 (001) -> OR = 5 <= 6, profit = 8 + 9  = 17
      cap = 3 (011): submasks are i=1 (010) and i=2 (001) -> OR = 3 <= 6, profit = 12 + 9 = 21
    

    The best cap is 3 (011), picking items 1 and 2 for a total gain of 21—beating cap = 6 (20) even though 3 < 6! Meanwhile, item 3 (mask = 7, binary 111) exceeds limit = 6 and never matches any cap.

    In Example 2 (masks = [16, 9, 12], limit = 6), every item turns on bit 3 (8) or bit 4 (16), whereas all caps [6, 5, 3] are 0 above bit 2, so no item matches any cap and best_profit stays 0.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def build_candidate_caps(limit: int) -> List[int]:
        """Return ~31 bitmask caps M <= limit that together cover every integer V <= limit."""
        # candidate_caps: list of integer bitmasks <= limit, e.g. [6, 5, 3] for limit = 6 (binary 110).
        # Include limit itself first to cover subsets whose combined bitwise OR equals limit exactly.
        candidate_caps = [limit]
    
        # For each 1-bit of limit, build a cap that matches limit above `bit`, clears `bit` to 0
        # (which guarantees cap < limit), and sets every bit below `bit` to 1 (allowing any lower bits).
        for bit in range(limit.bit_length()):
            is_bit_set = (limit >> bit) & 1
            if is_bit_set == 1:
                upper_prefix = (limit >> (bit + 1)) << (bit + 1)
                all_lower_ones = (1 << bit) - 1
                cap = upper_prefix | all_lower_ones
                candidate_caps.append(cap)
    
        return candidate_caps
    
    
    def max_profit_bitwise_or(profits: List[int], masks: List[int], limit: int) -> int:
        # Phase 1: Generate the O(log(limit)) candidate upper-bound bitmasks (at most 31 for limit <= 10^9).
        caps = build_candidate_caps(limit)
    
        # best_profit starts at 0 because choosing the empty subset (OR = 0, profit = 0) is always valid.
        best_profit = 0
    
        # Phase 2: For each cap, greedily sum EVERY item whose mask only uses 1-bits allowed by `cap`.
        for cap in caps:
            cap_profit = 0
            for profit, mask in zip(profits, masks):
                # Why (mask & cap) == mask instead of mask <= cap:
                # Every 1-bit of `mask` must also be a 1-bit of `cap` (submask test) so that
                # combining all matching items with bitwise OR can never turn on a bit outside `cap`.
                if (mask & cap) == mask:
                    cap_profit += profit
    
            if cap_profit > best_profit:
                best_profit = cap_profit
    
        return best_profit
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Picture each binary bit (1, 2, 4, 8, ...) as a toggle switch, and an item's bitmask (an integer whose binary 0/1 digits mark inactive/active switches) as the switches that item flips on. Merging items via bitwise OR (an operator | that sets a bit position to 1 if any selected item has a 1 there) activates the union of their switches, and the resulting integer must stay <= limit. Once we commit to a specific switch ceiling cap <= limit, every item whose mask is a submask of cap (an integer whose 1-bits are all 1-bits of cap, checked via (mask & cap) == mask) can be added for free without ever flipping on an unauthorized bit!

Enumerating all 2^n subsets is infeasible for n = 100,000, and greedily taking all items with masks[i] <= limit breaks because individually legal masks such as 4 (100), 2 (010), and 1 (001) combine via 4 | 2 | 1 = 7 (111) to exceed limit = 6. Checking every integer cap from 0 to limit would also require up to 10^9 scans. Instead, any integer V <= limit either equals limit or first falls below limit at one of limit's 1-bits (putting 0 there and arbitrary bits below it). Thus limit itself plus one "zero out a 1-bit and fill all lower bits with 1s" mask per 1-bit of limit—at most 31 candidate caps—covers every legal subset!

Here is a quick walkthrough on profits = [8, 12, 9], masks = [4, 2, 1], and limit = 6 (binary 110):

  1. Generate the candidate caps from 110: 6 (110, limit itself), 5 (101, bit 1 cleared and bit 0 set to 1), and 3 (011, bit 2 cleared and bits 1..0 set to 1).
  2. Sum submask items for each cap: cap = 6 (110) gathers 4 (100) and 2 (010) for 8 + 12 = 20; cap = 5 (101) gathers 4 and 1 for 8 + 9 = 17; cap = 3 (011) gathers 2 and 1 for 12 + 9 = 21.
  3. Return the maximum sum, 21.

Complexity

Let n be the number of items and K be the number of candidate caps (K = 1 + count of 1-bits in limit, so K <= 31 since limit <= 10^9 < 2^30).

  • Time: O(n * log(limit)) (at most 31 * n steps). Generating caps inspects at most 30 bit positions of limit, and for each of the K <= 31 caps we scan all n items once with O(1) bitwise AND and integer addition.
  • Space: O(log(limit)) (at most 31 integers). Only the short caps list and scalar accumulators are stored, using zero extra arrays proportional to n.

Edge cases

  • limit == 0: 0.bit_length() is 0, so [0] is the sole cap and only items with masks[i] == 0 contribute.
  • Every item has masks[i] > limit: no item can be a submask of any integer <= limit, returning 0 for the empty subset.
  • Individually valid masks that overflow together (masks = [1, 2], limit = 2): 1 (01) and 2 (10) never fit under the same cap (caps = [2, 1]), so only the higher-value item wins.
  • Winning cap drops a high or middle bit of limit: for limit = 8 (1000) and masks = [8, 7, 3, 1], cap = 7 (0111) takes three items while cap = 8 takes one; for limit = 13 (1101), clearing bit 2 produces cap = 11 (1011), which can beat both 13 and 7.
  • Repeated masks: bitwise OR is idempotent (ORing a value with itself leaves it unchanged: x | x == x), so duplicate submask items all safely add their profits.
  • 64-bit totals: 10^5 items worth 10^9 each can reach 10^14, handled natively by Python's arbitrary-precision integers (use int64_t / long in C++ or Java).

Common mistakes

  • Summing every item with masks[i] <= limit: masks below limit can still activate different bit positions whose union exceeds limit.
  • Using mask <= cap instead of (mask & cap) == mask: 1 <= 6 is numerically true, yet 1 (001) turns on bit 0 which is 0 in cap = 6 (110).
  • Forgetting parentheses around mask & cap in C/C++/Java: Python gives & higher precedence than ==, whereas C, C++, and Java bind == tighter than &; writing (mask & cap) == mask works safely in every language.
  • Clearing a 1-bit of limit without setting lower bits to 1: turning a 1-bit to 0 alone produces a submask of limit, missing valid subsets such as OR 3 (011) under limit = 6 (110).
  • Only clearing the topmost 1-bit of limit: the best subset can match limit's upper bits and diverge at an interior 1-bit, so every 1-bit of limit requires a candidate cap.

Follow-up questions

  • What adjustment is needed if individual item values are allowed to be zero or negative? Because bitwise OR only activates bits and can never clear a bit to rescue an invalid subset, an item with profits[i] <= 0 never helps satisfy OR <= limit and can only reduce total gain. Simply ignore items with profits[i] <= 0 (accumulate profit only when profit > 0 and (mask & cap) == mask) while keeping best_profit = 0 when the empty subset is permitted; if a non-empty subset were mandatory and all legal items had negative values, return max(profits[i] for i if masks[i] <= limit).
  • Suppose the rule instead required a non-empty subset whose bitwise AND is greater than or equal to limit—how would you adapt the candidate-mask idea? Swap the roles of 0 and 1: for a candidate floor mask F >= limit, collect every item that is a supermask of F (an integer containing 1 at every 1-bit of F, tested via (mask & F) == F). Whenever at least one item matches F, their bitwise AND retains all 1-bits of F and stays >= F >= limit. Candidate floors consist of limit itself plus, for each 0-bit b across the 30-bit mask range (0 <= b < 30), the mask matching limit above b, setting bit b to 1, and zeroing all bits below b—only scoring floors F matched by at least one item so the subset is non-empty.
  • If the item list stays fixed while thousands of different limit queries arrive, how can you precompute answers for fast per-query lookups? First aggregate profits by exact mask in a hash map so duplicate masks merge once. When masks fit in B bits where 2^B fits comfortably in RAM (for instance B <= 20, roughly 10^6 states), precompute dp[M] = total profit of all submasks of M in O(B * 2^B) time via Sum Over Subsets (SOS) dynamic programming (a dynamic programming sweep that accumulates values across submasks one bit dimension at a time):

python def precompute_submask_profits(profit_by_mask: List[int], num_bits: int) -> List[int]: dp = list(profit_by_mask) for bit in range(num_bits): for mask in range(1 << num_bits): if (mask >> bit) & 1: dp[mask] += dp[mask ^ (1 << bit)] return dp

Any query with `limit >= 2^B` immediately returns `dp[(1 << B) - 1]`, and any query with `limit < 2^B` takes the maximum of `dp[cap]` across its at most `B + 1` candidate caps in `O(B)` time per query!

Follow-up questions

Similar questions

More Concentric Ai interview questions

All 3 Concentric Ai questions →