Taro Logo

Maximum OR

#232 Most AskedMedium
0 views
Topics:
ArraysGreedy AlgorithmsBit Manipulation

You are given a 0-indexed integer array nums of length n and an integer k. In an operation, you can choose an element and multiply it by 2.

Return the maximum possible value of nums[0] | nums[1] | ... | nums[n - 1] that can be obtained after applying the operation on nums at most k times.

Note that a | b denotes the bitwise or between two integers a and b.

Example 1:

Input: nums = [12,9], k = 1
Output: 30
Explanation: If we apply the operation to index 1, our new array nums will be equal to [12,18]. Thus, we return the bitwise or of 12 and 18, which is 30.

Example 2:

Input: nums = [8,1,2], k = 2
Output: 35
Explanation: If we apply the operation twice on index 0, we yield a new array of [32,1,2]. Thus, we return 32|1|2 = 35.

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 1 <= k <= 15

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the size of the array and the values of the integers within it, and can the allowed number of operations exceed the size of the array or lead to integer overflow?
  2. Can the allowed number of operations be distributed across multiple elements, or must all operations be applied to a single element?
  3. Are there any zeros or negative numbers in the input array, and how should multiplication by two handle a value of zero?
  4. If the maximum possible bitwise OR total can be achieved using fewer than the allowed number of operations, is that valid, or must we utilize all operations?
  5. Should the function return the final bitwise OR sum of all elements in the array after the operations, or the maximum possible value of a single element after being modified?

Brute Force Solution

Approach

When facing a problem where we want to find the absolute maximum combined value using a specific number of allowed adjustments, the brute force approach is the ultimate try-everything method. We simply examine every single combination of allowed changes, calculate the resulting combined value for each one, and keep track of the largest result we encounter.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the original set of numbers without making any changes at all, and calculate their combined value.
  2. Next, imagine every possible way you are allowed to modify the numbers based on the rules given in the problem.
  3. Pick the first possible combination of modifications and apply them to the numbers.
  4. Calculate the combined value of this newly modified group.
  5. Compare this new value to the largest value you have found so far, and update your record if this new one is bigger.
  6. Undo those changes and move on to the very next possible combination of modifications.
  7. Repeat this process for every single valid combination of modifications until you have tested them all.
  8. Finally, once every single possibility has been checked, the largest value you recorded along the way is your answer.

Code Implementation

def maximum_or_brute_force(numbers, allowed_operations, multiplier):
    # We start with the base combined value with zero modifications applied
    current_maximum = 0
    for number in numbers:
        current_maximum |= number

    def generate_all_combinations(index, operations_left, current_numbers):
        nonlocal current_maximum
        if index == len(numbers) or operations_left == 0:
            combined_value = 0
            for number in current_numbers:
                combined_value |= number
            if combined_value > current_maximum:
                current_maximum = combined_value
            return

        # We explore the branch where we apply our multiplier to the current element
        modified_numbers = list(current_numbers)
        modified_numbers[index] *= (multiplier ** operations_left)
        generate_all_combinations(index + 1, 0, modified_numbers)

        # We explore the branch where we skip modifying the current element
        generate_all_combinations(index + 1, operations_left, current_numbers)

    # We test every valid combination of operations to find the global maximum
    for start_index in range(len(numbers)):
        generate_all_combinations(0, allowed_operations, list(numbers))

    return current_maximum

Big(O) Analysis

Time Complexity
O(2^n) – The brute force approach requires examining every single combination of allowed modifications to the n numbers in the input set. For each of the n elements, we independently decide whether to apply the adjustment or not, creating two choices per element. This generates approximately 2 to the power of n total possible modification combinations that must be tested. Multiplying the constant work per combination by this exponential number of subsets results in a total operation count that simplifies to O(2^n).
Space Complexity
O(1) – The brute force approach relies on a few scalar variables to keep track of the current modifications, the resulting combined value, and the largest result encountered so far. These variables consume a constant amount of extra memory regardless of the input size. No auxiliary data structures, temporary lists, or recursion stack frames scale with the input size N. Therefore, the total auxiliary space complexity remains constant.

Optimal Solution

Approach

To find the greatest possible bitwise combination after multiplying one chosen number by a power of two, we want to make the largest number possible as powerful as we can. The winning strategy is to figure out which number can contribute the most unique bits to the final combined total when shifted left.

Here's how the algorithm would work step-by-step:

  1. Think of each number as a collection of glowing lightbulbs, where each bulb represents a specific value and turning on bigger bulbs makes the total number much larger.
  2. We want to boost one single number by shifting its lightbulbs to the left, which makes all of its bulbs represent much higher values.
  3. To make the final combined result as bright as possible, we should focus our boosting power on the number that can turn on the most important, high-value bulbs that are not already turned on by the other numbers.
  4. We can easily figure out which bulbs are already lit across all numbers by looking at cumulative totals from left to right and from right to left.
  5. By combining what is lit to the left and right of any given number, we know exactly what new bulbs that specific number would unlock if we boosted it.
  6. We test this boosting idea on every single number one by one, calculate the resulting total brightness, and keep track of the maximum possible score we can achieve.
  7. Finally, we pick the absolute best result we found during our tests, which guarantees we made the smartest use of our boosting power.

Code Implementation

def maximum_or(number_list, shift_multiplier):
    array_length = len(number_list)
    prefix_bitwise_or = [0] * array_length
    suffix_bitwise_or = [0] * array_length

    # We precalculate cumulative OR values from the left to know existing bits.
    current_prefix_or = 0
    for index in range(array_length):
        prefix_bitwise_or[index] = current_prefix_or
        current_prefix_or |= number_list[index]

    # We precalculate cumulative OR values from the right to complete our bit map.
    current_suffix_or = 0
    for index in range(array_length - 1, -1, -1):
        suffix_bitwise_or[index] = current_suffix_or
        current_suffix_or |= number_list[index]

    maximum_result = 0
    multiplier_power = 1 << shift_multiplier

    # We test shifting each number to find which one yields the greatest OR total.
    for index in range(array_length):
        boosted_value = number_list[index] * multiplier_power
        combined_bitwise_or = prefix_bitwise_or[index] | boosted_value | suffix_bitwise_or[index]
        if combined_bitwise_or > maximum_result:
            maximum_result = combined_bitwise_or

    return maximum_result

Big(O) Analysis

Time Complexity
O(n) – To evaluate the best boosting option, we iterate through the input array of size n three separate times: once to compute cumulative OR totals from the left, once from the right, and a final pass to test shifting each number using those precalculated boundaries. Each of these passes consists of a single linear loop over the n elements without any nested iterations. This results in approximately 3 * n operations, which simplifies to Big O of n.
Space Complexity
O(N) – To implement the cumulative totals mentioned in step 4, we allocate two auxiliary prefix and suffix arrays of size N to store the bitwise OR combinations from both the left and right directions. Beyond these two arrays of size N, the algorithm only uses a few primitive variables for iteration and tracking the maximum score, requiring constant extra memory. Therefore, the total auxiliary space complexity is driven by these linear storage structures, resulting in O(N) space complexity where N is the number of elements in the input.

Edge Cases

Zero operations allowed (k = 0)
How to Handle:
The algorithm simply computes the bitwise OR of the original array without modifying any elements.
Single element array
How to Handle:
The element is multiplied by two k times, and the resulting single value is returned as the maximum OR.
Array containing only zeros
How to Handle:
Multiplying zero by two yields zero, so the result remains zero regardless of the number of operations.
Large number of operations (k is very large)
How to Handle:
Shifting any element by k positions will still fit within standard integer limits if managed carefully or using 64-bit integers.
All elements are equal
How to Handle:
The greedy approach will focus operations on a single chosen element to maximize its bit contributions relative to others.
Integer overflow from massive bit shifts
How to Handle:
Using 64-bit integer types ensures that multiplying by two k times does not cause overflow issues during bitwise operations.
High constraint on array size and value magnitude
How to Handle:
A precomputed prefix and suffix bitwise OR array approach ensures optimal linear or near-linear time complexity.
0/257 completed