[LeetCode] Maximum OR

2680. Maximum OR

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
long long maximumOr(vector<int>& nums, int k) {
vector<long long> dp(k+1, 0);
for(auto n : nums) {
vector<long long> dpp(k + 1, 0);
long long x = n;
for(int i = 0; i <= k; i++) {
for(int j = 0; j <= k - i; j++) {
dpp[i+j] = max(dpp[i+j], dp[i] | (x<<j));
}
}

swap(dp, dpp);
}


return *max_element(begin(dp), end(dp));
}
};


Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/13/PS/LeetCode/maximum-or/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.