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^5len(profits) == len(masks)1 <= profits[i] <= 10^90 <= masks[i] <= 10^90 <= limit <= 10^9
Step-by-step walkthrough
Understand the goal and why simple greedy fails
Each item
icontributes a positive valueprofits[i] >= 1and carries an integer bitmaskmasks[i]. We want to pick any subset of items whose combined bitwise OR (the operation|that sets a bit position to1whenever at least one chosen item has a1there) stays<= limit, maximizing the sum ofprofits[i]. Selecting no items at all produces bitwise OR0and total profit0.- Input:
profitsandmasksof lengthn <= 10^5, plus0 <= limit <= 10^9(at most30binary bits). - Output: maximum total profit (an integer
>= 0).
Testing all
2^nsubsets works only for tinyn. Meanwhile, greedily taking every item withmasks[i] <= limitfails because bitwise OR can merge smaller masks into a larger number that crosseslimit: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<= limitcompares whole integers. We need a clean bridge between the two.- Input:
Turn a numeric ceiling into a submask rule
Call
maska submask ofcapwhen every1-bit ofmaskis also a1-bit ofcap. In binary,masknever turns on a bit thatcapleaves0, which we test inO(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 <= limitas our allowed set of1-bits and greedily include every item whose mask is a submask ofcap:- Always valid: Because no chosen item turns on a bit outside
cap, their combined bitwise OR also stays insidecap, guaranteeingcombined_or <= cap <= limit. - Optimal for that
cap: Everyprofits[i]is positive, and adding more submask items can never violatecap, 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 ofV. So maximizing over allcapin0 .. limitgives the exact answer! The only catch is thatlimitcan reach10^9—far too many caps to scan one by one.- Always valid: Because no chosen item turns on a bit outside
Shrink a billion caps down to at most 31
Consider any valid OR outcome
V <= limitand compare its binary digits againstlimitfrom most significant bit down to bit0:- Case 1 (
V == limit):Vis a submask ofcap = limit. - Case 2 (
V < limit): Inspect the highest bit positionbitwhereVandlimitdiffer. BecauseV < limitand both numbers agree on every higher bit,limitmust have a1atbitwhileVhas a0atbit. Belowbit,Vcan contain any mix of0s and1s.
Therefore,
Vis guaranteed to be a submask of the integer formed by keepinglimit's prefix abovebit, placing0atbit, and filling every bit belowbitwith1: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:
cap < limitalways holds because they match abovebitandcaphas0wherelimithas1atbit(even all1s belowbitsum to(1 << bit) - 1 < (1 << bit)).- Every
Vthat first diverges belowlimitatbithas zero1-bits outsidecap, soVis a submask ofcap.
We construct just one
capper1-bit oflimit, pluslimititself. Becauselimit <= 10^9 < 2^30,limithas at most30bits, leaving at most 31 candidate caps!- Case 1 (
Build the candidate caps in Python
For each bit index
bitin0 .. limit.bit_length() - 1wherelimithas a1-bit:upper_prefix = (limit >> (bit + 1)) << (bit + 1)clearsbitand every lower position while keeping higher bits intact.all_lower_ones = (1 << bit) - 1sets positions0 .. bit - 1to1.upper_prefix | all_lower_onescombines both parts intocap.
Here is how that works on
limit = 6(binary110,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()is0, the loop runs zero times, andcandidate_capsis[0]—only items withmask == 0qualify.)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_capsSum matching items for each cap
For each
capreturned bybuild_candidate_caps(limit), scan allnitems once and addprofitwhenever(mask & cap) == mask. Track the highest sum across all caps, initializingbest_profit = 0for 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_profitTrace Examples 1 and 2 step by step
Let's trace Example 1 with
profits = [8, 12, 9, 14],masks = [4, 2, 1, 7], andlimit = 6(binary110):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 = 21The best cap is
3(011), picking items1and2for a total gain of21—beatingcap = 6(20) even though3 < 6! Meanwhile, item3(mask = 7, binary111) exceedslimit = 6and never matches any cap.In Example 2 (
masks = [16, 9, 12],limit = 6), every item turns on bit3(8) or bit4(16), whereas all caps[6, 5, 3]are0above bit2, so no item matches any cap andbest_profitstays0.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):
- Generate the candidate caps from
110:6(110,limititself),5(101, bit1cleared and bit0set to1), and3(011, bit2cleared and bits1..0set to1). - Sum submask items for each cap:
cap = 6(110) gathers4(100) and2(010) for8 + 12 = 20;cap = 5(101) gathers4and1for8 + 9 = 17;cap = 3(011) gathers2and1for12 + 9 = 21. - 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 most31 * nsteps). Generatingcapsinspects at most30bit positions oflimit, and for each of theK <= 31caps we scan allnitems once withO(1)bitwise AND and integer addition. - Space:
O(log(limit))(at most31integers). Only the shortcapslist and scalar accumulators are stored, using zero extra arrays proportional ton.
Edge cases
limit == 0:0.bit_length()is0, so[0]is the sole cap and only items withmasks[i] == 0contribute.- Every item has
masks[i] > limit: no item can be a submask of any integer<= limit, returning0for the empty subset. - Individually valid masks that overflow together (
masks = [1, 2], limit = 2):1(01) and2(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: forlimit = 8(1000) andmasks = [8, 7, 3, 1],cap = 7(0111) takes three items whilecap = 8takes one; forlimit = 13(1101), clearing bit2producescap = 11(1011), which can beat both13and7. - 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^5items worth10^9each can reach10^14, handled natively by Python's arbitrary-precision integers (useint64_t/longin C++ or Java).
Common mistakes
- Summing every item with
masks[i] <= limit: masks belowlimitcan still activate different bit positions whose union exceedslimit. - Using
mask <= capinstead of(mask & cap) == mask:1 <= 6is numerically true, yet1(001) turns on bit0which is0incap = 6(110). - Forgetting parentheses around
mask & capin C/C++/Java: Python gives&higher precedence than==, whereas C, C++, and Java bind==tighter than&; writing(mask & cap) == maskworks safely in every language. - Clearing a
1-bit oflimitwithout setting lower bits to1: turning a1-bit to0alone produces a submask oflimit, missing valid subsets such as OR3(011) underlimit = 6(110). - Only clearing the topmost
1-bit oflimit: the best subset can matchlimit's upper bits and diverge at an interior1-bit, so every1-bit oflimitrequires 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] <= 0never helps satisfyOR <= limitand can only reduce total gain. Simply ignore items withprofits[i] <= 0(accumulateprofitonly whenprofit > 0and(mask & cap) == mask) while keepingbest_profit = 0when the empty subset is permitted; if a non-empty subset were mandatory and all legal items had negative values, returnmax(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
0and1: for a candidate floor maskF >= limit, collect every item that is a supermask ofF(an integer containing1at every1-bit ofF, tested via(mask & F) == F). Whenever at least one item matchesF, their bitwise AND retains all1-bits ofFand stays>= F >= limit. Candidate floors consist oflimititself plus, for each0-bitbacross the30-bit mask range (0 <= b < 30), the mask matchinglimitaboveb, setting bitbto1, and zeroing all bits belowb—only scoring floorsFmatched 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
Bbits where2^Bfits comfortably in RAM (for instanceB <= 20, roughly10^6states), precomputedp[M]= total profit of all submasks ofMinO(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
- What adjustment is needed if individual item values are allowed to be zero or negative?
- 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?
- If the item list stays fixed while thousands of different limit queries arrive, how can you precompute answers for fast per-query lookups?
Similar questions
- Mismatched Indices in a Height Lineup
- Optimal Meetup Coordinates for Weighted Grid Travel
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance