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.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,2,1], k = 2
Output: 15
💡 Note: We can apply operations on nums[0] twice: 3 → 6 → 12. Then nums becomes [12,2,1] and the OR is 12|2|1 = 15.
Example 2 — Single Element
$ Input: nums = [2], k = 3
Output: 16
💡 Note: With only one element, apply all operations: 2 → 4 → 8 → 16. The OR is just 16.
Example 3 — Zero Operations
$ Input: nums = [7,3,5], k = 0
Output: 7
💡 Note: No operations allowed, so OR is 7|3|5 = 7.

Constraints

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

Visualization

Tap to expand
Maximum OR Problem INPUT nums array: 3 idx 0 2 idx 1 1 idx 2 Binary: 011 010 001 k = 2 Operation: multiply by 2 (left shift by 1 bit) Initial: 3|2|1 = 3 011|010|001 = 011 ALGORITHM STEPS 1 Compute Suffix OR suffix[i] = OR of nums[i+1..n] 2 Try Each Element Apply all k shifts to nums[i] 3 Calculate OR prefix | (nums[i]*2^k) | suffix 4 Track Maximum Keep best result found Trying i=0 (nums[0]=3): 3 * 2^2 = 12 12 = 1100 (binary) suffix = 2|1 = 3 = 011 1100 | 011 = 1111 = 15 Best result: 15 FINAL RESULT Optimal: Apply k=2 shifts to 3 Before: 3 2 1 After (3 * 4 = 12): 12 2 1 12 | 2 | 1 = 1100 | 0010 | 0001 = 1111 Output: 15 [OK] Maximum achieved! Key Insight: All k multiplications should be applied to a SINGLE element (greedy). Multiplying by 2 shifts bits left, setting new high bits that maximize OR. Use prefix/suffix arrays to compute OR in O(n) for each choice. TutorialsPoint - Maximum OR | Greedy with Prefix/Suffix Optimization
Asked in
Google 45 Amazon 38 Meta 32 Microsoft 28
23.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen