Problem · Dynamic Programming

Maximum Profit Under a Bitwise OR Limit

Learn this problem
MediumConcentric AI logoConcentric AIFULLTIMEOA

Problem statement

You are given equal-length arrays values and profits, and a nonnegative integer k.

Select any subset of indices. The subset is feasible when the bitwise OR of its selected values[i] is at most k. Its profit is the sum of its selected profits[i].

Return the maximum profit of a feasible subset. The empty subset is allowed, has bitwise OR 0, and has profit 0.

Function

maxProfitUnderOrLimit(values: int[], profits: int[], k: int) → long

Examples

Example 1

values = [1,2,4]profits = [5,6,7]k = 3return = 11

Select the first two items. Their OR is 3 and their total profit is 11. Selecting the third item would make the OR exceed the limit.

Example 2

values = [3,5,6]profits = [4,10,7]k = 7return = 21

All three items can be selected. Their OR is 7 and their total profit is 21.

Example 3

values = [1,2]profits = [-5,-1]k = 3return = 0

Every nonempty subset has negative profit, so the empty subset is optimal.

Constraints

  • 1 <= values.length == profits.length <= 2000
  • 0 <= values[i] < 1024
  • 0 <= k < 1024
  • -1000000 <= profits[i] <= 1000000
  • The answer fits in a signed 64-bit integer.

More Concentric AI problems

drafts saved locally
public long maxProfitUnderOrLimit(int[] values, int[] profits, int k) {
    // Write your code here.
}
values[1,2,4]
profits[5,6,7]
k3
expected11
checking account