question_slug
stringlengths 3
77
| title
stringlengths 1
183
| slug
stringlengths 12
45
| summary
stringlengths 1
160
⌀ | author
stringlengths 2
30
| certification
stringclasses 2
values | created_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| updated_at
stringdate 2013-10-25 17:32:12
2025-04-12 09:38:24
| hit_count
int64 0
10.6M
| has_video
bool 2
classes | content
stringlengths 4
576k
| upvotes
int64 0
11.5k
| downvotes
int64 0
358
| tags
stringlengths 2
193
| comments
int64 0
2.56k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
add-to-array-form-of-integer | Easy Beginner Friendly Python Solution :) | easy-beginner-friendly-python-solution-b-3hy6 | Easy Beginner Friendly Python Solution :)\n Describe your first thoughts on how to solve this problem. \n\n\n# Run Time\n Describe your approach to solving the | oshine_chan | NORMAL | 2023-07-30T20:14:50.726386+00:00 | 2023-08-02T18:35:47.611149+00:00 | 214 | false | # Easy Beginner Friendly Python Solution :)\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n\n# Run Time\n<!-- Describe your approach to solving the problem. -->\nBeats 98.87%\n\n# Memory\n<!-- Describe your approach to solving the problem. -->\nBeats 62.89%\n\n\n\n# Code\n```\nclass Solution:\n def addToArrayForm(self, num: List[int], k: int) -> List[int]:\n ans=[]\n n=len(num)\n while n>0 or k!=0:\n if n>0:\n n -=1\n k+=num[n]\n ans.append(k%10)\n k=k//10\n newlis=ans[::-1]\n return newlis\n```\n\n\n | 2 | 0 | ['Python3'] | 1 |
maximum-or | ✅Easiest solution | PREFIX-SUFFIX | c++ | easiest-solution-prefix-suffix-c-by-rish-fycl | IMPORTANT\nYou can watch the biggest sliding window series on entire internet just using single template by clicking my profile icon and checking my youtube cha | rishi800900 | NORMAL | 2023-05-13T16:04:13.161916+00:00 | 2023-05-26T17:12:49.336226+00:00 | 7,632 | false | #### IMPORTANT\nYou can watch the biggest sliding window series on entire internet just using single template by clicking my profile icon and checking my youtube channel link from the bio. ( I bet you can solve any sliding window question on leetcode after watching the series do share you thoughts on the same.)\nThankyou and happy leetcoding. \n## **INTUTION:**\n* Just calculate prefix OR (at each index prefix OR will contain OR of all its previous element) and suffix OR ( at each index suffix OR will contain OR of all its next elements.)\n\n* Now if you are lets say standing at current position then you have to find maximum OR value of taking\nOR of each value but after apply operation (multiply by 2 k times) then you have OR value of all elements\njust before of this current index is in prefix array and OR value of all element next to this index in suffix array.\n\n* So just check current number by multiplying by 2k times that whether it is generating maximum answer.\n\n#### **Let\'s take the test case: [12,9] and k=1**\n Prefix is: 0 12 13 \n Suffix is: 13 9 0 \n P= 2 (P=2*K)\n \n On calculating --> \n \n**for (int i = 0; i < n; i++) {\n res = max(res, pre[i] | (nums[i] * p) | suf[i + 1]); \n\t\t// res=max(res,(OR of all numbers before this index) * (current num multiplied with 2k times) * OR of all number after this index) //\n }**\n\t\n res= 0 If current num is multiped by 2 k times then answer will be= 25\n res= 25 If current num is multiped by 2 k times then answer will be= 30\n \n#### **Let\'s take the test case: [8,1,2] and k=2**\n Prefix is: 0 8 9 11 \n Suffix is: 11 3 2 0 \n P= 4 (P=2*k)\n \n On calculating --> \n \n**for (int i = 0; i < n; i++) {\n res = max(res, pre[i] | (nums[i] * p) | suf[i + 1]);\n }**\n res= 0 If current num is multiped by 2 k times then answer will be= 35\n res= 35 If current num is multiped by 2 k times then answer will be= 14\n res= 35 If current num is multiped by 2 k times then answer will be= 9\n\nso take maximum res value as answer.\n\n**NOTE\uD83D\uDCDD:** Some people are confused that whe multiply only current number with 2k times. It may be possible that we can get max answer by spreading multiply of 2 means you can multiply by 2 with multiple numbers why only to just one number.\n \n Dear your doubt is genuine but let you think that when we get maximum OR value\n \n* OR value is directly proportional to the greater we have a number. \n\n* Now suppose nums=[8,1,2] and k=2 if you think that instead of multiplying by 2k times you can multiply other numbers also means multiply one 2 by 8 another 2 by other number from 1 and 2 but you are wrong here you have to think critically here that I am raising each number to its maximum value by multiplying by 2k times and i am doing it for each number so the number which is generating maximum OR will be our final answer.\n\n* Actually 2k is also a number and we can maximise OR value if this 2k value is making a number maximum in our array.\n\t\n\n```\nlong long maximumOr(vector<int>& nums, int k) {\n int n = nums.size();\n vector<long long> pre(n + 1, 0); // Stores prefix bitwise OR values\n vector<long long> suf(n + 1, 0); // Stores suffix bitwise OR values\n pre[0] = 0;\n suf[n] = 0;\n long long res = 0;\n long long p = 1; // Used to calculate the power of 2, equivalent to x^k\n p = p << k; // Left shift k positions to calculate 2^k\n\n // Calculate prefix bitwise OR values\n for (int i = 0; i < n; i++) {\n pre[i + 1] = pre[i] | nums[i];\n }\n\n // Calculate suffix bitwise OR values\n for (int i = n - 1; i >= 0; i--) {\n suf[i] = suf[i + 1] | nums[i];\n }\n\n // Find the maximum result by iterating through the numbers\n for (int i = 0; i < n; i++) {\n//\tcout<<"res= "<<res<< " If current num is multiped by 2 k times then answer will be= "<<(pre[i] | (nums[i] * p) | suf[i + 1])<<endl; \n res = max(res, pre[i] | (nums[i] * p) | suf[i + 1]);\n }\n\n return res;\n}\n\n``` | 59 | 3 | [] | 15 |
maximum-or | [C++, Java, Python] Intuition with Explanation | Proof of Why? | Time: O(n) | c-java-python-intuition-with-explanation-g72t | Intuition\nMultiply by $2$ means left shift by $1$. We can left shift some numbers but at most $k$ times in total. To maximize the result we should generate set | shivamaggarwal513 | NORMAL | 2023-05-13T19:56:24.657806+00:00 | 2023-05-15T16:01:48.101483+00:00 | 1,950 | false | # Intuition\nMultiply by $2$ means left shift by $1$. We can left shift some numbers but at most $k$ times in total. To maximize the result we should generate set bits in the most significant part of numbers.\n\nTake this array\n```\n 5 - 000000000101\n 6 - 000000000110\n 9 - 000000001001\n20 - 000000010100\n23 - 000000010111\n```\nTo maximize the result, we should pick the numbers having their Left Most Set Bit (LMSB) farthest among all elements. $20$ and $23$ have their LMSB maximum among all elements. We should try to shift $20$ or $23$, $k$ times combined. Like shift $20$ $x$ times and shift $23$ $k-x$ times.\n\n---\n\nBut still why is shifting only one number $k$ times is more optimal?\n- Suppose $k=5$ and we shifted $20$, $5$ times and LMSB went further $5$ steps on the left.\nThe modified array becomes:\n```\n 5 - 000000000101\n 6 - 000000000110\n 9 - 000000001001\n640 - 001010000000\n 23 - 000000010111\n```\nThe LMSB of $640$ is $2^9=512$ so Bitwise-OR of array will be atleast $2^9$. It can be more depending upon other less significant bits.\n`ans >= 001000000000 (512)`\n- Now let\'s say we don\'t give all $k$ moves to a single number. Since, we are not giving all $k$ moves to single number, we will never be able to generate $2^9$ set bit in any number. And even if somehow we generate all lower set bits $2^8, 2^7, 2^6, ...$ by distributing $k$ moves to different numbers, answer will still be less than $2^9$.\n$2^8 + 2^7 + 2^6 + ... + 2^0 = 2^9 - 1 < 2^9$\n\nTherefore, giving all $k$ moves to single element (that too having largest LMSB) is the most optimal.\n\n# Approach\n- Shift each number $k$ times and calculate Bitwise-OR.\n- To make this fast, pre-compute Bitwise-OR of elements before it (prefix) and after it (suffix).\n- Take maximum of them.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int n = nums.size();\n long long result = 0;\n vector<int> prefix(n + 1), suffix(n + 1);\n for (int i = 1; i < n; i++) {\n prefix[i] = prefix[i - 1] | nums[i - 1];\n suffix[n - i - 1] = suffix[n - i] | nums[n - i];\n }\n for (int i = 0; i < n; i++) {\n result = max(result, prefix[i] | ((long long)nums[i] << k) | suffix[i]);\n }\n return result;\n }\n};\n```\n```Java []\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n int n = nums.length;\n long result = 0;\n int[] prefix = new int[n + 1];\n int[] suffix = new int[n + 1];\n for (int i = 1; i < n; i++) {\n prefix[i] = prefix[i - 1] | nums[i - 1];\n suffix[n - i - 1] = suffix[n - i] | nums[n - i];\n }\n for (int i = 0; i < n; i++) {\n result = Math.max(result, prefix[i] | ((long)nums[i] << k) | suffix[i]);\n }\n return result;\n }\n}\n```\n```Python []\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n n, result = len(nums), 0\n prefix, suffix = [0] * (n + 1), [0] * (n + 1)\n for i in range(1, n):\n prefix[i] = prefix[i - 1] | nums[i - 1]\n suffix[n - i - 1] = suffix[n - i] | nums[n - i]\n for i in range(n):\n result = max(result, prefix[i] | (nums[i] << k) | suffix[i])\n return result\n```\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$ | 40 | 0 | ['Bit Manipulation', 'Prefix Sum', 'C++', 'Java', 'Python3'] | 6 |
maximum-or | [Java/C++/Python] Easy One Pass | javacpython-easy-one-pass-by-lee215-zatt | Intuition\nThe best plan is to double the same number k times\nthis will shift the leftmost bit to left k bits.\n\n\n# Explanation\nright[i] = A[i + 1] * A[i + | lee215 | NORMAL | 2023-05-13T16:48:15.829149+00:00 | 2023-05-13T16:51:33.391309+00:00 | 3,107 | false | # **Intuition**\nThe best plan is to double the same number `k` times\nthis will shift the leftmost bit to left `k` bits.\n<br>\n\n# **Explanation**\n`right[i] = A[i + 1] * A[i + 2] * ... * A[n - 1]`\n`left[i] = A[0] * A[1] * ... * A[i - 1]`\n\nSo the result for doubling `A[i]` is\n`left[i] | A[i] << k | right[i]`.\n\nOne pass `A` and return the result.\n<br>\n\n# **Complexity**\nTime `O(n)`\nSpace `O(n)`\n<br>\n\n**Java**\n```java\n public long maximumOr(int[] A, int k) {\n int n = A.length, right[] = new int[n], left = 0;\n long res = 0;\n for (int i = n - 2; i >= 0; --i) {\n right[i] = right[i + 1] | A[i + 1];\n }\n for (int i = 0; i < n; i++) {\n res = Math.max(res, left | (long)A[i] << k | right[i]);\n left |= A[i];\n }\n return res;\n }\n```\n\n**C++**\n```cpp\n long long maximumOr(vector<int> &A, int k) {\n int n = A.size(), left = 0;\n vector<int> right(n);\n long res = 0;\n for (int i = n - 2; i >= 0; --i) {\n right[i] = right[i + 1] | A[i + 1];\n }\n for (int i = 0; i < n; i++) {\n res = max(res, left | (long)A[i] << k | right[i]);\n left |= A[i];\n }\n return res;\n }\n```\n\n**Python**\n```py\n def maximumOr(self, A: List[int], k: int) -> int:\n res, left, n = 0, 0, len(A)\n right = [0] * n\n for i in range(n - 2, -1, -1):\n right[i] = right[i + 1] | A[i + 1]\n for i in range(n):\n res = max(res, left | A[i] << k | right[i])\n left |= A[i]\n return res\n```\n | 37 | 1 | ['C', 'Python', 'Java'] | 8 |
maximum-or | O(1) space: keep track of bits, super simple to understand and detailed explanation | o1-space-keep-track-of-bits-super-simple-mx2g | Glossary:\n- bit set: ith bit is set means the ith bit equals one \n- highest bit of a number: highest i for which the ith bit is set (eg. in 1001 the highest b | ricola | NORMAL | 2023-05-13T16:28:30.402359+00:00 | 2023-05-14T08:52:10.235605+00:00 | 2,727 | false | Glossary:\n- *bit set*: ith bit is set means the ith bit equals one \n- *highest bit of a number*: highest `i` for which the ith bit is set (eg. in 1001 the highest bit is the 4th bit)\n- *the OR* : `nums[0] | nums[1] | ... | nums[n - 1]`, after one operation (not necessarily the final result)\n\n\nExplanation\n\n1. When you do `nums[0] | nums[1] | ... | nums[n - 1]`, what you get as a result is a number which will have the `i`th bit set if any of `nums[i]` has this bit set.\n2. We want to maximise the result. What does it mean? It means that we want to have all the higher bits as high as possible. So any solution that maximizes the higher bits will find the solution.\n3. From point 2. **we can deduce what we need to multiply only one number `k` times**. Why?\n 1. Lets say bit `b` is the highest bit of all the numbers in `nums`.\n 2. Let\'s say we picked a number (let\'s call it `x`) from nums that has this highest bit and applied the first operation on it\n 3. This means that now the OR will have the highest bit = `b+1` \n 4. For the next operation, we have to to chose `x` again. Why? Because if we chose `x` again then the OR will have `b+2` as the highest bit and it\'s impossible have a higher OR by chosing another number than `x` (since the highest bit is `b` if you chose another one the OR will have max `b+1` as the highest bit)\n 5. Repeat the same logic `k` times\n\n4. Now that we deduced that we just have to pick one number and double it `k` times, the question becomes way easier. You simply have to **iterate through all numbers and chose the one for which the answer will be the highest** (we also deduced that it is one of the numbers that has the max highest bit, but we don\'t need this info)\n5. Now the only remaining problem is how to we compute OR in an efficient way? \n 1. From point 1., we can simply iterate on each number and fill an array keeping track if bit `b` is set or not\n 2. We can precompute the OR bits by filling this array. Computing the value of OR is easy, we just convert the array to a number\n 3. When we multiply a number by `2^k` we simply shift its bits `k` positions higher, then we can get the result of chosing this number by adding its bits to the array.\n 4. Now there is one last trick. In 3. since we shift `num` we could by mistake consider a bit of its initial value as being set, but it was maybe the only number that had this bit. We just have to slightly modify our array to store the count of numbers having this bit. Then before shifting we decrease the count of this bit. If this count == 0 in the array it means this bit is not set.\n\n\n```\nclass Solution {\n // normally the worst case would be 10^9 * 2^ 15, so 45 bits max but I put more just in case (so that we can handle any long)\n\tprivate static final int MAX_BITS = 63;\n\n public long maximumOr(int[] nums, int k) {\n\t\n\t\t// precompute the array of bits\n\t\t// originalBits[i] = how many elements in nums have bit i set to one\n int[] originalBits = new int[MAX_BITS];\n for (int num : nums) {\n for(int i = 0; num > 0; i++){\n if(num%2 == 1) originalBits[i]++;\n num /= 2;\n }\n }\n\n long max = 0;\n for (int num : nums) {\n int[] bits = Arrays.copyOf(originalBits, MAX_BITS);\n for(int i = 0; num > 0; i++){\n if(num%2 == 1){ // if ith bit set\n\t\t\t\t\t// remove its old value\n bits[i]--;\n\t\t\t\t\t// add its new one\n bits[i+k]++;\n }\n num /= 2;\n }\n\t\t\t// convert bits to a number\n long result = 0;\n for (int i = 0; i < MAX_BITS; i++) {\n if(bits[i] > 0) result += (1L << i);\n }\n max = Math.max(result, max);\n }\n\n return max;\n\n }\n}\n```\n\nTime complexity : `O(n)` since we simply iterate on `nums`\nSpace complexity: `O(1)` We only use one array of constant size\n\n\n# Note \nFollowing the discussion with @dinar below, from point 2. you can solve it with a different algorithm (but same complexity) by iterating on the bits and filtering out candidates that wouldn\'t produce the highest bits in the answer. \n\t<details>\n\t<summary>Reveal alternative solution</summary>\n```\nclass Solution {\n\n private int bitAt(int num, int i){\n return (num >> i) & 1;\n }\n\n public long maximumOr(int[] nums, int k) {\n // small improvement to limit the number of bits to check\n // we could also iterate first over all numbers to see what is the actual highest bit\n int MAX_BITS = 30 +k;\n\n Set<Integer> candidates = new HashSet<>();\n\n // precompute the array of bits\n int[] bits = new int[MAX_BITS];\n for (int num : nums) {\n candidates.add(num);\n for(int i = 0; num > 0; i++){\n if(num%2 == 1) bits[i]++;\n num /= 2;\n }\n }\n\n for (int i = MAX_BITS - 1; i >= 0; i--) {\n Set<Integer> withBit = new HashSet<>();\n long bitMask = i >= k ?\n 1L << (i-k) : // looking for a bit in position i-k\n i << 31; // mask impossible to match\n for (Integer candidate : candidates) {\n if((bitMask & candidate) > 0) withBit.add(candidate);\n else {\n // we look if this bit would be set in the final result with this candidate shifted\n if(bits[i] - bitAt(candidate, i) > 0) withBit.add(candidate);\n }\n }\n\n // if withBit.size = 0, no candidate better than the others for this bit, so we keep all the previous candidates\n if(withBit.size() >= 1){\n candidates = withBit;\n }\n\n if(candidates.size() == 1) break; // we can stop early we found a unique winner\n }\n\n // take an random candidate from all the ones that provide the maximum\n int winner = candidates.iterator().next();\n\n for(int i = 0; winner > 0; i++){\n if(winner%2 == 1){ // if ith bit set\n // remove its old value\n bits[i]--;\n // add its new one\n bits[i+k]++;\n }\n winner /= 2;\n }\n // convert bits to a number\n long result = 0;\n for (int i = 0; i < MAX_BITS; i++) {\n if(bits[i] > 0) result += (1L << i);\n }\n\n\n return result;\n\n }\n```\n\t | 30 | 1 | ['Java'] | 7 |
maximum-or | Explained - Very simple & easy to understand solution | explained-very-simple-easy-to-understand-55c0 | Up vote if you like the solution \n# Approach \n1. Evaluate 2^k\n2. Then calculate prefix & suffix bit wise value and store it\n3. check each number by multiply | kreakEmp | NORMAL | 2023-05-13T16:15:46.909832+00:00 | 2023-05-13T17:54:32.571368+00:00 | 4,696 | false | <b>Up vote if you like the solution </b>\n# Approach \n1. Evaluate 2^k\n2. Then calculate prefix & suffix bit wise value and store it\n3. check each number by multiplying 2^k, if it has max ans or not.\n\nQ. Why this works :\nAns : When we multiply a number by 2 then this equal to shifting the values to the left by 1 places. \nSo to have a largest value we should shift a single number to the k number of times which end up with max value possible.\nnow we don\'t know exactly which value to shift k times, so we check the same for all possible numbers and keep tracking the max value.\n\n# Code\n```\n\n long long maximumOr(vector<int>& nums, int k) {\n long long ans = 0, mul = 1;\n vector<long long> pre(nums.size(), 0), suf(nums.size(), 0);\n pre[0] = nums[0]; suf[nums.size()-1] = nums.back();\n for( int i = 1; i < nums.size(); ++i) {\n pre[i] = pre[i-1] | nums[i];\n suf[nums.size() - i - 1] = suf[nums.size()-i] | nums[nums.size() - i - 1];\n }\n for(int i = 0; i < k; ++i){ mul *= 2; }\n for(int i = 0; i < nums.size(); ++i){\n long long x = nums[i]*mul;\n if(i-1 >= 0) x = x | pre[i-1];\n if(i+1 < nums.size()) x = x | suf[i+1];\n ans = max(ans, x);\n }\n return ans;\n }\n\n```\n\n<b> Here is an article of my last interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon:\nhttps://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted | 24 | 3 | ['C++'] | 8 |
maximum-or | Java easy with explanation. | java-easy-with-explanation-by-rupdeep-084r | Approach\nTo solve this problem, we can use the approach of calculating prefix and suffix sums. For each element in the array, we can calculate the maximum poss | Rupdeep | NORMAL | 2023-05-13T16:02:35.122237+00:00 | 2023-05-13T16:02:35.122276+00:00 | 1,764 | false | # Approach\nTo solve this problem, we can use the approach of calculating prefix and suffix sums. For each element in the array, we can calculate the maximum possible value of nums[0] | nums[1] | ... | nums[n - 1] by multiplying it by 2^k and bitwise ORing it with the prefix sum of the elements before it and the suffix sum of the elements after it.\n\nHere\'s the step-by-step algorithm:\n\n1. Calculate the prefix sum of the array. For each index i, the prefix sum prefix[i] is equal to the bitwise OR of all elements nums[0] | nums[1] | ... | nums[i].\n\n2. Calculate the suffix sum of the array. For each index i, the suffix sum suffix[i] is equal to the bitwise OR of all elements nums[i] | nums[i+1] | ... | nums[n-1].\n\n3. For each index i in the array, calculate the maximum possible value of nums[0] | nums[1] | ... | nums[n - 1] by multiplying nums[i] by 2^k and bitwise ORing it with prefix[i-1] and suffix[i+1]. Take the maximum value obtained from all indices.\n\n4. Return the maximum value obtained in step 3.\n\n# Complexity\n- Time complexity:\nO(N);\n\n- Space complexity:\nO(N);\n\n# Code\n```\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n int n = nums.length;\n int[] prefix = new int[n];\n int[] suffix = new int[n];\n \n prefix[0] = nums[0];\n for (int i = 1; i < n; i++) {\n prefix[i] = prefix[i-1] | nums[i];\n }\n \n suffix[n-1] = nums[n-1];\n for (int i = n-2; i >= 0; i--) {\n suffix[i] = suffix[i+1] | nums[i];\n }\n \n long maxOr = 0;\n for (int i = 0; i < n; i++) {\n long or = ((long) nums[i]) * (1L << k) | (i > 0 ? prefix[i-1] : 0) | (i < n-1 ? suffix[i+1] : 0);\n maxOr = Math.max(maxOr, or);\n }\n \n return maxOr;\n }\n}\n``` | 11 | 1 | ['Java'] | 1 |
maximum-or | Dynamic programming not working || solution using prefix array | dynamic-programming-not-working-solution-09iv | Intuition\n Describe your first thoughts on how to solve this problem. \nThis approach is not working for test case -> 6,9,8 and k = 1\nthe ans should be 31 and | satyamkant2805 | NORMAL | 2023-05-13T16:03:28.524554+00:00 | 2023-05-16T10:10:52.520628+00:00 | 1,261 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis approach is not working for test case -> 6,9,8 and k = 1\nthe ans should be 31 and my code is giving 30... \nto get answer we multiply 8 by 2 so array will be [6,9,16]\n\nthe dp code is not taking 9|16 (25) as return value instead it is taking 18|8 (26) which is wrong.\nthis is happening because we are maximising our answer in aur recursive code and it is taking 26 as our final value instead of 25 (which gives us the right answer).\n\n\n# Wrong Code\n```\nclass Solution {\n \n long long dp[100009][20];\n\n /// to calculate the power of 2\n long long cal(int id){\n long long val = 1LL;\n while(id--){\n val*=(2LL);\n }\n return val;\n }\n \n long long rec(vector<int> &arr,int id,int k){\n if(id>=arr.size())\n return 0;\n if(dp[id][k]!=-1)\n return dp[id][k];\n long long ans = 0;\n /// how many times should I multiply arr[id] with 2....\n for(int i = 0;i<=k;i++){\n ans = max(ans,(cal(i)*arr[id])|(rec(arr,id+1,k-i)));\n }\n \n return dp[id][k] = ans;\n \n }\n \npublic:\n long long maximumOr(vector<int>& nums, int k) {\n memset(dp,-1,sizeof(dp));\n return rec(nums,0,k);\n }\n};\n```\n\n\n# Correct Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n long long ans = 0;\n vector<long long> suff(nums.size()+1);\n long long curr = 0;\n for(int i=nums.size()-1;i>=0;i--){\n curr|=nums[i];\n suff[i] = curr;\n }\n\n curr = 0;\n\n for(int i=0;i<nums.size();i++){\n long long temp = curr;\n temp |= (nums[i]*(1LL<<k));\n ans = max(ans,(temp)|(suff[i+1]));\n curr |= nums[i];\n }\n\n return ans;\n }\n};\n\n```\n | 10 | 1 | ['Dynamic Programming', 'Recursion', 'C++'] | 2 |
maximum-or | Python simple greedy O(n) Time O(1) Memory | python-simple-greedy-on-time-o1-memory-b-ica4 | \n\n# Code\n\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n cur = 0\n saved = 0\n for num in nums:\n | Yigitozcelep | NORMAL | 2023-05-13T16:00:36.493461+00:00 | 2023-05-13T16:23:10.964003+00:00 | 1,347 | false | \n\n# Code\n```\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n cur = 0\n saved = 0\n for num in nums:\n saved |= num & cur\n cur |= num\n \n max_num = 0\n \n for num in nums:\n max_num = max(max_num, saved | (cur & ~num) | num << k)\n return max_num\n \n\n``` | 9 | 0 | ['Greedy', 'Python3'] | 6 |
maximum-or | Step by step explanation || best Solution | step-by-step-explanation-best-solution-b-nwjh | Intuition\n1. We start with the most significant bit (30th bit assuming the maximum value of elements in nums is less than 2^30) and iterate downwards.\n2. In e | raunakkodwani | NORMAL | 2023-05-13T17:39:19.902638+00:00 | 2023-05-13T17:39:19.902688+00:00 | 496 | false | # Intuition\n1. We start with the most significant bit (30th bit assuming the maximum value of elements in `nums` is less than 2^30) and iterate downwards.\n2. In each iteration, we count the number of elements in `nums` that have the current bit set to 1.\n3. If the count is greater than `k` or if setting the current bit to 1 results in a value less than the current maximum value, we skip this bit.\n4. Otherwise, we update the maximum value by setting the current bit to 1 and subtract the count from `k`.\n5. We continue this process for each bit in descending order until we have exhausted `k` operations or iterated through all the bits.\n6. Finally, we return the maximum value obtained.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Initialize a variable named `max_val` to store the maximum possible value.\n2. Initialize a variable named `mask` to 0. This mask will help us keep track of the significant bits in the numbers.\n3. Iterate from the 30th bit (assuming the maximum value of nums elements is less than 2^30) to 0 in descending order. In each iteration, perform the following steps:\n - Initialize a variable named `count` to 0. This variable will keep track of how many numbers in nums have the current bit set to 1.\n - Iterate through each number in the nums array. If the bit at the current position is set to 1, increment the count variable.\n - If count is greater than k or if (mask | (1 << bit)) is less than max_val, continue to the next iteration.\n - Update max_val to (max_val | (1 << bit)).\n - Subtract count from k.\n - Set the bit at the current position in the mask to 1.\n4. Return the value of max_val as the maximum possible value.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int n=nums.size();\nlong long pre[n + 1], suf[n + 1];\n long long sol, pow = 1;\n for (int i = 0; i < k; i++){\n pow*=2;\n }\n \n pre[0] = 0;\n for (int i = 0; i < n; i++){\n pre[i + 1] = pre[i] | nums[i];\n }\n suf[n] = 0;\n for (int i = n - 1; i >= 0; i--){\n suf[i] = suf[i + 1] | nums[i];\n }\n sol= 0;\n for (int i = 0; i < n; i++)\n sol = max(sol, pre[i] | (nums[i] * pow) | suf[i + 1]);\n \n return sol; \n }\n};\n```\n\n | 8 | 0 | ['C++'] | 0 |
maximum-or | EASY C++ USING PREFIX AND SUFFIX SUM | easy-c-using-prefix-and-suffix-sum-by-sp-k99f | Intuition\nWe have to check on each element weather we can give multiply it for k times. Multiplying single element k time will give more larger result.\n\n# Ap | sparrow_harsh | NORMAL | 2023-05-13T16:03:15.561901+00:00 | 2023-05-13T16:06:59.336023+00:00 | 2,371 | false | # Intuition\nWe have to check on each element weather we can give multiply it for k times. Multiplying single element k time will give more larger result.\n\n# Approach\nwe will store prefix and suffix or of each index in order to minimise time complexity.\n\nafter that we can iterate on each index multifly it with 2 for k times and take new or (pre[i] | val | suf[i+1]) it will give the or of array. we will store maximum in ret variable.\n\n# Complexity\n- Time complexity:\nO(n)\n\n\n# Code\n```\nclass Solution {\npublic:\n \n long long maximumOr(vector<int>& nums, int k) {\n \n int n=nums.size();\n int x=2;\n vector<long long>pre(n+1,0),suff(n+1,0);\n long long res, po = 1;\n \n\n for (int i = 0; i < k; i++){\n po *= x;\n }\n \n \n for (int i = 0; i < n; i++){\n pre[i + 1] = pre[i] | nums[i];\n }\n \n suff[n] = 0;\n for (int i = n - 1; i >= 0; i--){\n suff[i] = suff[i + 1] | nums[i];\n }\n \n res = 0;\n for (int i = 0; i < n; i++){\n res = max(res, pre[i] | (nums[i] * po) | suff[i + 1]);\n }\n \n \n return res;\n }\n};\n```\n\nPLEASEEE UPVOTEE IF IT HELPSS | 8 | 1 | ['C++'] | 3 |
maximum-or | Python 3 || 7 lines, w/explanation || T/S: 99% / 99% | python-3-7-lines-wexplanation-ts-99-99-b-13hj | Here\'s the plan:\n1. We determine the maximum number of bits for elements innums.\n2. We compile those elements innumsthat have the maximum number of bits (n) | Spaulding_ | NORMAL | 2023-05-17T17:02:17.882876+00:00 | 2024-06-19T23:40:25.237536+00:00 | 610 | false | Here\'s the plan:\n1. We determine the maximum number of bits for elements in`nums`.\n2. We compile those elements in`nums`that have the maximum number of bits (`n`) in the array`cands`. (The answer will be determined by left-shifting one of these elements.)\n3. We iterate through`nums`, keeping track of the bits seen (`bits`) and bits seen more than once (`extraBits`). \n\n4. We assess which element`c`of`cands`provides the *maximum or* after left-shifting`k`bits by: (a) xoring the bits of`c`from`bits`; (b) unioning the bits of`c << k`to`bits`to reflect the left-shifting of `c`; and (c) unioning the bits of`extraBits`to`bits`to replace bits incorrectly removed by the xoring. \n\n.\n```\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n\n bits, extraBits, mx, cands = 0, 0, 0, []\n n = 1<<int(log2(max(nums))) # <-- 1)\n\n for num in nums:\n if num >= n: cands.append(num) # <-- 2)\n\n extraBits|= num&bits # <-- 3)\n bits|= num #\n \n return max(bits^c | # <-- 4a)\n c << k | # <-- 4b)\n extraBits for c in cands) # <-- 4c)\n```\n[https://leetcode.com/problems/maximum-or/submissions/1294048595/](https://leetcode.com/problems/maximum-or/submissions/1294048595/)\n\nI could be wrong, but I think that time complexity is *O*(*N*) and space complexity is *O*(*N*), in which *N* ~ `len(nums).\n | 7 | 0 | ['Python', 'Python3'] | 1 |
maximum-or | Prefix & Suffix - Detailed Explaination | prefix-suffix-detailed-explaination-by-t-ar8u | \nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n n, res = len(nums), 0\n pre, suf = [0] * n, [0] * n\n # calcu | __wkw__ | NORMAL | 2023-05-14T06:11:30.958441+00:00 | 2023-05-14T07:31:57.682620+00:00 | 229 | false | ```\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n n, res = len(nums), 0\n pre, suf = [0] * n, [0] * n\n # calculate the prefix OR \n for i in range(n - 1): pre[i + 1] = pre[i] | nums[i]\n # calculate the suffix OR\n for i in range(n - 1, 0, -1): suf[i - 1] = suf[i] | nums[i]\n # iterate each number\n # we apply k operations on nums[i], i.e. shift k bits to the left\n # why not applying on multiple numbers? \n # first in binary format, multiplying a number by 2 is shifting 1 bit to the left\n # e.g. 0010 (2) -> 0100 (4)\n # e.g. 0101 (5) -> 1010 (10)\n # second, in OR operation, we wish there is a 1 as left as possible\n # which produces the greater value\n # hence, we apply on the same number to achieve the max value\n # which produces the max OR value\n # now we calculate nums[0] | nums[1] | ... | nums[n - 1]\n # by utilising the prefix OR and suffix OR\n # the reason is simple\n # we precompute the result instead of calculate the OR values on each iteration\n for i in range(n): res = max(res, pre[i] | nums[i] << k | suf[i])\n return res\n```\n\n**p.s. Join us on the LeetCode The Hard Way Discord Study Group for timely discussion! Link in bio.** | 6 | 0 | ['Prefix Sum', 'Python'] | 0 |
maximum-or | ✅ Easy Segment Tree Approach| Intuitive Solution| C++ code | easy-segment-tree-approach-intuitive-sol-m87r | Intuition\nSince its a range query and update so we should think of Segment tree approach\n# Approach\nSince its given that we can multiply the array elements b | ampish | NORMAL | 2023-05-13T16:06:49.834836+00:00 | 2023-05-13T16:13:13.104523+00:00 | 1,265 | false | # Intuition\nSince its a range query and update so we should think of Segment tree approach\n# Approach\nSince its given that we can multiply the array elements by 2, it indirectly means that we can right shift the array elements k times.\nNow,\nFirstly we should think how many values should be affected by the operation?\nSo the answer to this is it is always optimal to right shift that value which has the most significant bit as leftmost as possible then the other elements\n\nSo to do so,\nWe build the segment tree for Bitwise OR operation and for each value we right shift that particular element k times and check for the maximum value\n\n# Complexity\n- Time complexity:\nO(n*logn)\n\n- Space complexity:\nO(n)\n\n# Code\n```\n#define ll long long\n#include <vector>\nusing namespace std;\n\nclass SegmentTree {\nprivate:\n vector<ll> tree;\n ll n;\n \npublic:\n SegmentTree(ll sz) {\n n = sz;\n tree.resize(4*n);\n }\n \n void update(ll idx, ll val) {\n updateUtil(1, 0, n-1, idx, val);\n }\n \n ll query(int l, int r) {\n return queryUtil(1, 0, n-1, l, r);\n }\n \nprivate:\n void updateUtil(ll node, ll start, ll end, ll idx, ll val) {\n if (start == end) {\n tree[node] = val;\n } else {\n ll mid = (start + end) / 2;\n if (idx <= mid) {\n updateUtil(2*node, start, mid, idx, val);\n } else {\n updateUtil(2*node+1, mid+1, end, idx, val);\n }\n tree[node] = tree[2*node] | tree[2*node+1];\n }\n }\n \n ll queryUtil(ll node, ll start, ll end, ll l, ll r) {\n if (r < start || end < l) {\n return 0;\n }\n if (l <= start && end <= r) {\n return tree[node];\n }\n ll mid = (start + end) / 2;\n ll orLeft = queryUtil(2*node, start, mid, l, r);\n ll orRight = queryUtil(2*node+1, mid+1, end, l, r);\n return orLeft | orRight;\n }\n};\n\n\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n ll n=nums.size();\n SegmentTree st(n);\n for (int i = 0; i < n; i++) {\n st.update(i, nums[i]);\n }\n \n ll ans=0;\n for(int i=0;i<n;i++){\n int val=nums[i];\n st.update(i,((1ll * val) << k));\n ll anss=st.query(0,n-1);\n ans=max(ans,anss);\n st.update(i,val);\n }\n \n \n return ans;\n \n\n }\n};\n```\n\nPlease UPVOTE it you liked my solution :) | 6 | 0 | ['C++'] | 0 |
maximum-or | WA on new testcases | Try All Ways | Bottom Up & Top Down DP | Try all ways | C++ | Java | wa-on-new-testcases-try-all-ways-bottom-09jc1 | Idea:\nKnapSack -> Pick or not pick\nPick, how many times we can multiply current number by 2, then do OR\nSkip, just do OR and move to next\n\nC++\nTop Down\n\ | hwaiting_dk | NORMAL | 2023-05-13T16:02:06.049531+00:00 | 2023-05-16T14:08:22.142176+00:00 | 1,409 | false | **Idea:**\nKnapSack -> Pick or not pick\nPick, how many times we can multiply current number by 2, then do `OR`\nSkip, just do `OR` and move to next\n\nC++\n**Top Down**\n```\n// TC: O(N * K * K)\n// SC: O(N * K)\n#define ll long long\nclass Solution {\n ll memo[100001][16];\n\n ll rec(vector<int> &arr, int i, int k){\n if(i == arr.size()) return 0;\n if(memo[i][k] !=- 1) return memo[i][k];\n \n ll maxi = arr[i] | rec(arr, i + 1, k);;\n \n for(ll j = 1; j <= k; j++){\n ll value = arr[i]; \n ll cur = (value << j); // it equals to value * pow(2, j)\n \n maxi = max(maxi, cur | rec(arr, i + 1, k - j));\n }\n return memo[i][k] = maxi;\n }\npublic:\n long long maximumOr(vector<int>& arr, int k){\n memset(memo, -1, sizeof(memo));\n return rec(arr, 0, k);\n }\n};\n```\n**Bottom Up**\n```\n#define ll long long\nclass Solution {\npublic:\n long long maximumOr(vector<int>& arr, int k){\n int n = arr.size();\n ll dp[n + 1][k + 1];\n \n for(int i = n; i >= 0; i--){\n for(int j = 0; j < k + 1; j++){\n if(i == n){\n dp[i][j] = 0;\n continue;\n }\n \n ll maxi = arr[i] | dp[i + 1][j];\n \n for(ll l = 1; l <= j; l++){\n ll value = arr[i]; \n ll cur = (value << l);\n\n maxi = max(maxi, cur | dp[i + 1][j - l]);\n }\n dp[i][j] = maxi;\n }\n }\n return dp[0][k];\n }\n};\n```\n**Java**\n```\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n long[][] memo = new long[nums.length][k + 1];\n for (int i = 0; i < nums.length; i++) {\n Arrays.fill(memo[i], -1);\n }\n return rec(nums, 0, k, memo);\n }\n \n private long rec(int[] nums, int i, int k, long[][] memo) {\n if (i == nums.length) {\n return 0;\n }\n if (memo[i][k] != -1) {\n return memo[i][k];\n }\n \n long maxi = nums[i] | rec(nums, i + 1, k, memo);\n \n for (int j = 1; j <= k; j++) {\n long value = nums[i];\n long cur = (value << j);\n maxi = Math.max(maxi, cur | rec(nums, i + 1, k - j, memo));\n }\n memo[i][k] = maxi;\n return maxi;\n }\n}\n``` | 6 | 0 | ['Dynamic Programming'] | 2 |
maximum-or | O(n) Time Simple Greedy Algorithm Beats 100% | on-time-simple-greedy-algorithm-beats-10-zbv6 | Intuition\n Describe your first thoughts on how to solve this problem. \nWe will always use a single element to apply k operations on it \n# Approach\n Describ | hakkiot | NORMAL | 2024-01-22T15:03:57.620946+00:00 | 2024-01-23T03:43:28.902411+00:00 | 86 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe will always use a single element to apply $$k$$ operations on it \n# Approach\n<!-- Describe your approach to solving the problem. -->\nApply $$k$$ steps on every $$a[i]$$ and return the maximum of all\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code\n```\n//~~~~~~~~~~~~~MJ\xAE\u2122~~~~~~~~~~~~~\n#include <bits/stdc++.h>\n#pragma GCC optimize("Ofast")\n#pragma GCC optimize("unroll-loops")\n#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx")\n#define Code ios_base::sync_with_stdio(0);\n#define by cin.tie(NULL);\n#define Hayan cout.tie(NULL);\n#define append push_back\n#define all(x) (x).begin(),(x).end()\n#define allr(x) (x).rbegin(),(x).rend()\n#define vi vector<ll>\n#define yes cout<<"YES";\n#define no cout<<"NO";\n#define vb vector<bool\n#define vv vector<vector<int>>\n#define ul unordered_map<int,vi>\n#define ub unordered_map<int,bool>\n#define ui unordered_map<int,int>\n#define sum(a) accumulate(all(a),0)\n#define add insert\n#define ll long long\n#define endl \'\\n\'\n#define pi pair<int,int>\n#define ff first\n#define ss second\nclass Solution {\npublic:\n long long maximumOr(vector<int>& a, ll k) \n {\n Code by Hayan\n ll n=a.size();\n\n //prefix arr and suffix arr\n vi pre,suf;\n\n ll c=0;\n for (ll i=0;i<n;i++)\n {\n //prefix bitwise or calculating\n pre.append(c);\n c|=a[i];\n }\n\n c=0;\n for (ll i=n-1;i>-1;i--)\n {\n //suffix bitwise or calculating\n suf.append(c);\n c|=a[i];\n }\n\n ll ans=0;\n for (ll i=0;i<n;i++)\n {\n // if a[i] is used\n ll used=1LL*(a[i])*(1<<(k));\n ans=max(ans,0LL|pre[i]|suf[n-i-1]|used);\n }\n return ans;\n \n\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
maximum-or | SUFFIX || PREFIX || C++ || EASY TO UNDERSTNAD | suffix-prefix-c-easy-to-understnad-by-ga-cxa0 | Code\n\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int n = nums.size(),i;\n if(n==1)return ((nums[0]*1LL)<<k | ganeshkumawat8740 | NORMAL | 2023-05-13T18:44:13.049845+00:00 | 2023-05-13T18:49:44.467231+00:00 | 721 | false | # Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int n = nums.size(),i;\n if(n==1)return ((nums[0]*1LL)<<k);\n vector<int> p(n,0),s(n,0);\n p[0] = nums[0];\n for(i = 1; i < n; i++){\n p[i] = (p[i-1]|nums[i]);\n }\n s[n-1] = nums[n-1];\n for(i = n-2; i >=0; i--){\n s[i] = (s[i+1]|nums[i]);\n }\n long long int ans = 0;\n for(int i = 0; i < n; i++){\n if(i==0){\n ans = max(ans,((nums[i]*1LL)<<k)|s[i+1]);\n }else if(i==n-1){\n ans = max(ans,((nums[i]*1LL)<<k)|p[i-1]);\n }else{\n ans = max(ans,((nums[i]*1LL)<<k)|s[i+1]|p[i-1]);\n }\n }\n return ans;\n }\n};\n``` | 4 | 0 | ['Array', 'Dynamic Programming', 'Suffix Array', 'Prefix Sum', 'C++'] | 1 |
maximum-or | Using Prefix Method | C++ Easy Solution | using-prefix-method-c-easy-solution-by-k-mudc | Intuition\n Describe your first thoughts on how to solve this problem. \nWe know that there should be only one number that should be multipled by 2^k as every t | kaptan01 | NORMAL | 2023-05-13T16:05:38.191892+00:00 | 2023-05-13T16:13:08.395622+00:00 | 1,093 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe know that there should be only one number that should be multipled by 2^k as every time we multiply a number by 2 there will be shift in a bit of that number, so that number became larger and larger.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe use prefix and postfix arrays to store **OR** of numbers before and after for a number\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int n = nums.size(); \n vector<int> pre(n, 0), post(n, 0); \n \n for(int i=1; i<n; i++) pre[i] = (pre[i-1] | nums[i-1]); \n for(int i = n-2; i>=0; i--) post[i] = (post[i+1] | nums[i+1]); \n \n long long res = 0; \n \n for(int i=0; i<n; i++){\n long long num = nums[i]; \n num *= pow(2, k); \n res = max(res, pre[i]|num|post[i]);\n }\n return res;\n }\n};\n``` | 4 | 0 | ['Dynamic Programming', 'Prefix Sum', 'C++'] | 0 |
maximum-or | Python | Greedy | python-greedy-by-aryonbe-spca | Code\n\nfrom collections import Counter\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n counter = [0]*32\n for num in | aryonbe | NORMAL | 2023-05-13T16:02:33.033907+00:00 | 2023-05-13T16:02:33.033949+00:00 | 907 | false | # Code\n```\nfrom collections import Counter\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n counter = [0]*32\n for num in nums:\n for i in range(32):\n counter[i] += num & 1\n num = num >> 1\n res = 0\n for j, num in enumerate(nums):\n tmp = num\n for i in range(32):\n counter[i] -= tmp & 1\n tmp = tmp >> 1\n tmpres = 0\n for i in range(32):\n tmpres += (counter[i] > 0)*(1<<i)\n tmpres = tmpres | (num << k)\n res = max(res, tmpres)\n tmp = num\n for i in range(32):\n counter[i] += tmp & 1\n tmp = tmp >> 1\n return res\n``` | 4 | 1 | ['Python3'] | 1 |
maximum-or | ✅ [ CPP ] | Very Easy Solution | No DP | cpp-very-easy-solution-no-dp-by-rushi_mu-163l | \n#### Intuition:\n Intuition of this problem is little bit tricky\n In this question we need to do k operations on any elements. In an operation, we choose an | rushi_mungse | NORMAL | 2023-05-13T16:01:43.873085+00:00 | 2023-05-13T16:05:33.414953+00:00 | 1,003 | false | \n#### Intuition:\n* Intuition of this problem is little bit tricky\n* In this question we need to do k operations on any elements. In an operation, we choose an element and `multiply it by 2`. \n* Above information says in one operation we `shift all bits to left by 1` -> `2 * num == (num << 1)` \n* In our solution we just do `all operation on only one element` because we shift all bits left sides by k times then our answer is maximise.\n\n----\n \n#### Approach:\n* We check one by one element shifing k times left\n* Claculate maximum result\n\n----\n\n# Complexity\n- Time complexity: $$O(n * 70)$$\n- Space complexity: $$O(70)$$\n\n----\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n vector<int> freq(70, 0);\n \n // count the number of set bit at perticular pos\n for(auto &x : nums) {\n for(int i = 0; i < 32; i++) \n if(x & (1ll << i)) freq[i]++;\n }\n \n \n long long int ans = 0;\n for(auto &x : nums) {\n // here we shift bits left side by k times\n for(int i = 0; i < 32; i++)\n if(x & (1ll << i)) {\n freq[i]--;\n freq[i + k]++;\n }\n // here calculate the result after shifting bits left side\n long long int cur = 0;\n for(int i = 0; i < 64; i++) {\n cur = cur + ((freq[i] ? 1ll : 0ll) << i); // cur = cur + (freq[i] ? 1ll : 0ll) * pow(2, i);\n }\n // store maximum answer \n ans = max(cur, ans);\n \n // set all bits initial state\n for(int i = 0; i < 32; i++) \n if(x & (1ll << i)) {\n freq[i]++;\n freq[i + k]--;\n }\n }\n \n return ans;\n }\n};\n\n```\nHope this helps \uD83D\uDE04.\n\n----\n> If you helpful, please upvote \uD83D\uDD3C\uD83D\uDD3C | 4 | 1 | ['C++'] | 3 |
maximum-or | Greedy and prefix OR | greedy-and-prefix-or-by-hobiter-bqt5 | Intuition\n Describe your first thoughts on how to solve this problem. \nYou need to put all k to one element to make sure the lest most 1;\nHowever, the elemen | hobiter | NORMAL | 2023-05-15T06:28:32.489419+00:00 | 2023-05-15T06:28:32.489462+00:00 | 279 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nYou need to put all k to one element to make sure the lest most 1;\nHowever, the element is not necessary the largest element, eg:\n[100000001,\n100000010,\n100]\nk = 1,\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\nO(N)\n# Code\n```\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n int n = nums.length, pre[] = new int[n], post[] = new int[n];\n long res = 0L;\n for (int i = 1; i < n; i++) {\n // pre[i] is the prefix or for i, nums[0] | ... | nums[i - 1]\n pre[i] = pre[i - 1] | nums[i - 1]; \n // post[i] is the suffix or for i, nums[i + 1] | ... | nums[n - 1]\n post[n - 1 - i] = post[n - 1 - i + 1] | nums[n - 1 - i + 1];\n }\n for (int i = 0; i < n; i++) {\n res = Math.max(res, pre[i] | (long) nums[i] << k | post[i]);\n }\n return res;\n }\n}\n``` | 3 | 0 | ['Java'] | 0 |
maximum-or | Python Elegant & Short | O(n) | Prefix Sum | python-elegant-short-on-prefix-sum-by-ky-5lhk | Complexity\n- Time complexity: O(n)\n- Space complexity: O(n)\n\n# Code\n\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n n | Kyrylo-Ktl | NORMAL | 2023-05-14T20:32:35.512977+00:00 | 2023-05-14T20:32:35.513018+00:00 | 401 | false | # Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n n = len(nums)\n\n right = [0] * n\n for i in reversed(range(n - 1)):\n right[i] = right[i + 1] | nums[i + 1]\n\n left = [0] * n\n for i in range(1, n):\n left[i] = left[i - 1] | nums[i - 1]\n\n return max(\n l | (num << k) | r\n for l, num, r in zip(left, nums, right)\n )\n``` | 3 | 0 | ['Prefix Sum', 'Python', 'Python3'] | 0 |
maximum-or | max( bits from multiple numbers OR bits from any number not in current number OR num LSH k ) | max-bits-from-multiple-numbers-or-bits-f-qo9c | Time complexity: $O(n)$ - we iterate over nums twice\n- Space complexity: $O(1)$ - we use constant auxiliary memory with 6 temporary variables\ngolang []\nfunc | dtheriault | NORMAL | 2023-05-13T16:25:10.623922+00:00 | 2023-05-13T17:52:37.207456+00:00 | 197 | false | - Time complexity: $O(n)$ - we iterate over nums twice\n- Space complexity: $O(1)$ - we use constant auxiliary memory with 6 temporary variables\n```golang []\nfunc maximumOr(nums []int, k int) int64 {\n // O(n) - determine bits that appear in multiple numbers and those that appear in any number\n appearsInMultiple := 0\n appearsInAny := 0\n for _, num := range nums {\n appearsInMultiple |= appearsInAny & num\n appearsInAny |= num\n }\n\n // O(n) - determine maximum number we can form by taking\n // bits that appear in multiple numbers, bits that appear\n // in any number that don\'t appear in current num, and bits\n // we get from LSH of current num by k\n max := int64(appearsInAny)\n for _, num := range nums {\n n := int64(appearsInMultiple) | int64(appearsInAny & ^num) | int64(num) << k\n if n > max {\n max = n\n }\n }\n\n return max\n}\n```\n```python3 []\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n # O(n) - determine bits that appear in multiple numbers and those\n # that appear in any number\n appearsInMultiple = 0\n appearsInAny = 0\n for num in nums:\n appearsInMultiple |= appearsInAny & num\n appearsInAny |= num\n\n # O(n) - determine maximum number we can form by taking\n # bits that appear in multiple numbers, bits that appear\n # in any number that don\'t appear in current num, and bits\n # we get from LSH of current num by k\n maximum = appearsInAny\n for num in nums:\n maximum = max(maximum, appearsInMultiple | appearsInAny & ~num | num << k)\n\n return maximum\n```\n```typescript []\nconst maximumOr = (nums: number[], k: number): number => {\n // O(n) - determine bits that appear in multiple numbers and those\n // that appear in any number\n let appearsInMultiple = 0n, appearsInAny = 0n\n for (let num of nums) {\n appearsInMultiple |= appearsInAny & BigInt(num)\n appearsInAny |= BigInt(num)\n }\n\n // O(n) - determine maximum number we can form by taking\n // bits that appear in multiple numbers, bits that appear\n // in any number that don\'t appear in current num, and bits\n // we get from LSH of current num by k\n let maximum = appearsInAny\n for (let num of nums) {\n const n = appearsInMultiple | appearsInAny & ~BigInt(num) | BigInt(num) << BigInt(k)\n if (n > maximum) {\n maximum = n\n }\n }\n\n return Number(maximum)\n}\n```\n```javascript []\nconst maximumOr = (nums, k) => {\n // O(n) - determine bits that appear in multiple numbers and those\n // that appear in any number\n let appearsInMultiple = 0n, appearsInAny = 0n\n for (let num of nums) {\n appearsInMultiple |= appearsInAny & BigInt(num)\n appearsInAny |= BigInt(num)\n }\n\n // O(n) - determine maximum number we can form by taking\n // bits that appear in multiple numbers, bits that appear\n // in any number that don\'t appear in current num, and bits\n // we get from LSH of current num by k\n let maximum = appearsInAny\n for (let num of nums) {\n const n = appearsInMultiple | appearsInAny & ~BigInt(num) | BigInt(num) << BigInt(k)\n if (n > maximum) {\n maximum = n\n }\n }\n\n return Number(maximum)\n}\n```\n\nSolutions for other problems in biweekly contest 104:\n\n- [2678. Number of Senior Citizens\n](/problems/number-of-senior-citizens/solutions/3520347/go-extract-11th-12th-character-and-check-if-60/)\n- [2679. Sum in a Matrix\n](/problems/sum-in-a-matrix/solutions/3520365/go-sort-rows-in-onm-log-m-time-then-determine-max-per-column/) | 3 | 0 | ['Go', 'TypeScript', 'Python3', 'JavaScript'] | 0 |
maximum-or | Easy C++ solution using prefix and suffix | easy-c-solution-using-prefix-and-suffix-x1e32 | Intuition\nApply the operation k time on single element only.\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nMaintain prefix and s | Sachin_Kumar_Sharma | NORMAL | 2024-01-29T13:04:38.601060+00:00 | 2024-01-29T13:04:38.601086+00:00 | 10 | false | # Intuition\nApply the operation k time on single element only.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nMaintain prefix and suffix vector which keep the track of the OR of all the elements left to i and right to i respectively.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int i,n=nums.size();\n\n vector<int> prefix(n,0),suffix(n,0);\n\n for(i=1;i<n;i++){\n prefix[i]=prefix[i-1] | nums[i-1];\n }\n\n for(i=n-2;i>=0;i--){\n suffix[i]=suffix[i+1] | nums[i+1];\n }\n\n long long ans=0;\n\n for(i=0;i<n;i++){\n long long x=nums[i];\n x<<=k;\n\n ans=max(ans,prefix[i] | x| suffix[i]);\n }\n\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
maximum-or | Why (num << k) explanation | Simple & Easy step by step thinking process | Easy | Prefix Sum | C++ | why-num-k-explanation-simple-easy-step-b-oxgv | Intuition\n Describe your first thoughts on how to solve this problem. \nWe start by checking the binary representation of the numbers.\n\nLet\'s take an exampl | initial1ze | NORMAL | 2023-08-23T18:40:52.005369+00:00 | 2023-08-24T04:47:21.222299+00:00 | 58 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe start by checking the binary representation of the numbers.\n\nLet\'s take an example: \n\n`nums = [1,2], k = 2`\n\nWe write the numbers in their binary represenations.\n\n1 -> `1` | 2 -> `10`\n\n**Observation 1:** The maximum number that can be made is by multiplying the number with maximum number of bits in it\'s binary representation.\n\nIn this example, we have k = 2, We have 3 cases:\n- We use both operations for `idx: 0` then we will convert 1 (`1`) -> 4 (`100`) and our result will be `4 | 2 = 6`\n- We use one operation for `idx: 0` and the second one for `idx: 1` then we will convert 1 (`1`) -> 2 (`10`) and 2 (`10`) -> 4 (`100`) and our result will be `2 | 4 = 6`\n- We use both for `idx: 1` then we will convert 2 (`10`) -> 8 (`1000`) and our result will be `1 | 8 = 9`\n\nIt can be observed that performing the operations on the number which has highest number of bits can give us the maximum result, which is `9` for this example.\n\nHere\'s the second case what if we have multiple numbers sharing the maximum number of bits.\n\nLet\'s take an example again:\n\n`nums = [12,9], k = 2`\n\nHere we have 12 -> `1100` and 9 -> `1001`\n\nBoth of them have maximum number of bits which is 4. Here we have k = 2.\n\n - Supose we apply first operation on `idx: 0` then it will become 12 (`1100`) -> 24 (`11000`) and the other number would be 9 (`1001`)\n - Now we only applied one operation and we still have one operation left (initially `k=2`)\n - Now our array is `[24, 9]`\n - Now we can see that 24 (`11000`) has maximum number of bits and according to the `Observation 1`, applying all operations on it will give us the maximum result for the array -> `[24, 9]`\n - After apply the rest of the operations on `24` our array becomes `[48, 9]` our final result becomes `48 | 9 = 57`\n\nNow we apply the same thing we `idx: 1`\n- Apply one operation then it will become 9 (`1001`) -> 18 (`10010`).\n- Our new array is `[12, 18]`\n- Now we can see that 18 (`10010`) has maximum number of bits and according to the `Observation 1`, applying all operations on it will give us the maximum result for the array -> `[12, 18]`\n- After apply the rest of the operations on `18` our array becomes `[12, 36]` our final result becomes `12 | 36 = 44`\n\nNow our final answer for the array `[12, 9]` and `k=2` will be the maximum of `57` and `44` which is `57`.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Base Case: If the size of the input is `1` we can just return `nums[0]*k`\n- Now we loop over the input array and for each index we use all the operations on the current index that is `nums[idx]*k`\nTo calculate the answer for this index, we also need the OR of the rest of the elements. For this we use prefix and suffix array.\n- We build the prefix and suffix array.\n```\n vector<long long> pref(n+1), suff(n+1);\n \n\n for (int i = 0; i < n; i++) {\n pref[i + 1] = pref[i] | nums[i];\n }\n\n for (int i = n - 1; i >= 0; i--) {\n suff[i] = suff[i + 1] | nums[i];\n }\n```\n- To calucalte the answer for the current index we have three thing to consider `pref[i]`, `nums[idx]*k` and `suff[i+1]`.\n- The result for current index will be `pref[i] | nums[idx] * k | suff[i+1]`\n- Our final answer will be the maximum of the results we get from each index.\n\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n- Here we are computing prefix OR on the fly.\n```\nclass Solution {\npublic:\n typedef long long ll;\n\n long long maximumOr(vector<int> &nums, int k) {\n int n = nums.size();\n if(n == 1)\n return nums[0]*1LL << k;\n\n vector<ll> suff(n+1);\n \n for (int i = n - 1; i >= 0; i--) {\n suff[i] = suff[i + 1] | nums[i];\n }\n\n int preOR = 0;\n\n ll ans = 0;\n for(int i =0; i < n; i++) {\n ll curr = nums[i]*1LL << k;\n ll tmp = preOR | curr | suff[i+1];\n preOR |= nums[i];\n ans = max(ans, tmp);\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Bit Manipulation', 'Prefix Sum', 'C++'] | 0 |
maximum-or | CPP Solution using prefix OR and suffix OR | cpp-solution-using-prefix-or-and-suffix-phxr8 | \n# Code\n\nclass Solution {\npublic:\n long long maximumOr(vector<int>& l, int k) {\n vector<long long> nums(l.size());\n int n = nums.size(); | sxmbaka | NORMAL | 2023-05-16T09:20:35.673996+00:00 | 2023-05-16T09:20:35.674034+00:00 | 556 | false | \n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& l, int k) {\n vector<long long> nums(l.size());\n int n = nums.size();\n for (int i = 0; i < n; i++) nums[i] = l[i];\n vector<int> pr(n), sf(n);\n pr[0] = nums[0];\n sf[n-1]=nums[n-1];\n for (int i = 1; i < n; i++) \n pr[i] = pr[i - 1] | nums[i];\n for (int i = n - 2; i >= 0; i--) \n sf[i] = sf[i + 1] | nums[i];\n nums.insert(nums.begin(), 0);\n pr.insert(pr.begin(), 0);\n sf.insert(sf.begin(), 0);\n pr.push_back(0);\n sf.push_back(0);\n for (int i = 1; i < n + 1; i++) {\n nums[i] = nums[i] * pow(2, k);\n }\n long long ans = INT_MIN;\n for (int i = 1; i < n + 1; i++) {\n long long x = nums[i] | pr[i - 1] | sf[i + 1];\n ans = max(ans, x);\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 2 |
maximum-or | 🔥Java || Prefix - Suffix | java-prefix-suffix-by-neel_diyora-sfq3 | Complexity\n- Time complexity: O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(N)\n Add your space complexity here, e.g. O(n) \n\n# Co | anjan_diyora | NORMAL | 2023-05-14T05:14:43.764221+00:00 | 2023-05-14T05:14:43.764253+00:00 | 398 | false | # Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n if(nums.length == 1) {\n return (long)nums[0] << k;\n }\n\n long[] prefix = new long[nums.length];\n prefix[0] = nums[0];\n\n for(int i = 1; i < nums.length; i++) {\n prefix[i] = prefix[i-1] | (long)nums[i];\n }\n\n long[] suffix = new long[nums.length];\n suffix[nums.length - 1] = nums[nums.length - 1];\n\n for(int i = nums.length - 2; i >= 0; i--) {\n suffix[i] = suffix[i+1] | (long)nums[i];\n }\n\n long ans = Math.max(((long)nums[0] << k) | suffix[1], ((long)nums[nums.length - 1] << k) | prefix[nums.length - 2]);\n\n for(int i = 1; i < nums.length - 1; i++) {\n long n = ((long)nums[i] << k) | prefix[i-1] | suffix[i+1];\n ans = Math.max(ans, n);\n }\n return ans;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
maximum-or | Python3 Solution | python3-solution-by-motaharozzaman1996-65ef | \n\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n cur = 0\n saved = 0\n for num in nums:\n saved | | Motaharozzaman1996 | NORMAL | 2023-05-13T18:39:23.269620+00:00 | 2023-05-13T18:39:23.269681+00:00 | 149 | false | \n```\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n cur = 0\n saved = 0\n for num in nums:\n saved |= num & cur\n cur |= num\n \n max_num = 0\n \n for num in nums:\n max_num = max(max_num, saved | (cur & ~num) | num << k)\n return max_num\n \n``` | 2 | 1 | ['Python', 'Python3'] | 1 |
maximum-or | Prefix - Suffix with intuitiion -> why to increase only one element why not spread it. | prefix-suffix-with-intuitiion-why-to-inc-hv30 | Intuition\n1. or operation\n2. k is very small\n3. multiply with 2 -> left shifting\n\ncorrect statement multiplying the number with left most msb is most benif | Ar_2000 | NORMAL | 2023-05-13T18:12:58.565170+00:00 | 2023-05-13T18:13:57.653396+00:00 | 136 | false | # Intuition\n1. or operation\n2. k is very small\n3. multiply with 2 -> left shifting\n\ncorrect statement multiplying the number with left most msb is most benificial as it will make the or more bigger as it has MSB at.\n\nnow there can be multiple numbers with left most msbs. We have to choose one of them. \nWhich one will be best option to choose ?\n- the one which after choosing if done an OR with rest of the numbers will give max OR result / will have lesser \nimposition of bits\n\nwhy not spread k accross multiple numbers with left most msb? \n- even if we do k-1 with a number and 1 with another then we are reducing the or potentially by 2^k.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int n = nums.size();\n\n vector<long long> prefixOr(n, 0), suffixOr(n, 0);\n\n for (int i = 1; i < n; i++) {\n prefixOr[i] = (prefixOr[i-1]|nums[i-1]);\n } \n\n for (int i = n-2; i >= 0; i--) {\n suffixOr[i] = (suffixOr[i+1]|nums[i+1]);\n }\n\n long long p = pow(2,k);\n long long ans = 0;\n for (int i = 0; i < n; i++) {\n ans = max(ans, (prefixOr[i]|suffixOr[i])|(nums[i]*p));\n }\n\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
maximum-or | [C++] why my Code was not working! , don't use "or" instead of "|" | c-why-my-code-was-not-working-dont-use-o-mqvy | From today onwards,i\'ll remember or == || \nfor logic or always |\nvery disappointed :(\n# Code\n\nclass Solution {\npublic:\n #define ll long long\n ll | Pathak_Ankit | NORMAL | 2023-05-13T16:54:11.343886+00:00 | 2023-05-13T16:54:11.343929+00:00 | 252 | false | From today onwards,i\'ll remember or == || \nfor logic **or** always **|**\nvery disappointed :(\n# Code\n```\nclass Solution {\npublic:\n #define ll long long\n ll memo[100001][16];\n long long rec(int i,int j,vector<int>&nums,int k)\n {\n if(i>=nums.size()) return 0;\n if(memo[i][j] !=- 1) return memo[i][j];\n \n long long with=0;\n long long without=0;\n without=nums[i] or rec(i+1,j,nums,k) ;\n for(int a=1;a<=j;a++)\n {\n if(j-a>=0)\n {\n long long temp = rec(i+1,j-a,nums,k) ;\n ll cur=(ll)nums[i]*pow(2,a) ;\n temp =temp or cur;\n // cout<<i<<" : "<<a<<" "<<temp<<endl;\n with=max(temp,with);\n } \n }\n \n // cout<<i<<" : "<<j<<" :: "<<with<<" "<<without<<endl;\n return memo[i][j]=max(with,without);\n }\n long long maximumOr(vector<int>& nums, int k) {\n memset(memo, -1, sizeof(memo));\n return rec(0,k,nums,k);\n }\n};\n``` | 2 | 0 | ['Dynamic Programming', 'Recursion', 'Memoization', 'C++'] | 0 |
maximum-or | JS Solution | js-solution-by-cf2-irxu | Intuition\n Describe your first thoughts on how to solve this problem. \nDon\'t forget to use BigInt. That\'s why I didn\'t get it right in the contest.\n# Appr | cf2 | NORMAL | 2023-05-13T16:31:32.156935+00:00 | 2023-05-13T16:33:04.443821+00:00 | 109 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nDon\'t forget to use BigInt. That\'s why I didn\'t get it right in the contest.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar maximumOr = function(nums, k) {\n let n = nums.length;\n let prev = [0n];\n let post = [0n];\n for (let i = 0; i < n; i++) prev.push(prev[prev.length - 1] | BigInt(nums[i]))\n for (let i = n - 1; i >= 0; i--) post.push(post[post.length - 1] | BigInt(nums[i]));\n let res = 0n;\n for (let i = 0; i < n; i++) {\n let cur = BigInt(nums[i]);\n let v = cur * BigInt(2 ** k) | prev[i] | post[n - i - 1];\n if (v > res) {\n res = v;\n }\n }\n return Number(res);\n};\n``` | 2 | 0 | ['JavaScript'] | 0 |
maximum-or | Simple Java solution. | simple-java-solution-by-codehunter01-wy4r | \n\n# Code\n\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n int n = nums.length;\n long[] prefix = new long[n];\n long | codeHunter01 | NORMAL | 2023-05-13T16:03:46.623631+00:00 | 2023-05-13T16:03:46.623672+00:00 | 534 | false | \n\n# Code\n```\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n int n = nums.length;\n long[] prefix = new long[n];\n long[] suffix = new long[n];\n prefix[0] = 0;\n suffix[n-1] = 0;\n for(int i= 1;i<n;i++)\n {\n prefix[i] = prefix[i-1]|nums[i-1];\n }\n for(int i=n-2;i>=0;i--)\n {\n suffix[i] = suffix[i+1]|nums[i+1];\n }\n long max =0;\n for(int i=0;i<n;i++)\n {\n long val = prefix[i]|suffix[i];\n long v = nums[i]*(long)Math.pow(2,k);\n max = Math.max(max,val|v);\n }\n return max;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
maximum-or | EASY C++ SOLUTION | easy-c-solution-by-10_adi-o5x3 | Intuition\nBY MULTIPLYING NUMBER BY 2 WILL INCREASE ITS VALUE SO RATHER THAN INCREASING DIFFERNT NUMBERS IN AN ARRAY , WE SHOULD INCREASE INDIVIDUAL NUMBER AND | 10_Adi | NORMAL | 2024-07-17T10:07:47.976966+00:00 | 2024-07-17T10:07:47.977033+00:00 | 8 | false | # Intuition\nBY MULTIPLYING NUMBER BY 2 WILL INCREASE ITS VALUE SO RATHER THAN INCREASING DIFFERNT NUMBERS IN AN ARRAY , WE SHOULD INCREASE INDIVIDUAL NUMBER AND TAKE MAX OF THEM WHICH WILL PROVIDE US WITH MAXIMUM OR VALUE.\n\n# Approach\nPREFIX, SUFFIX OR \n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\npublic:\n #define ll long long int \n long long maximumOr(vector<int>& arr, int k) {\n int n=arr.size();\n vector<ll>pre(n+1,0);\n pre[0]=arr[0];\n ll ans=0;\n for(int i=1;i<n;i++){\n pre[i]= pre[i-1] | arr[i];\n ans|=arr[i];\n }\n vector<ll>suff(n+1,0);\n suff[n-1]=arr[n-1];\n for(int i=n-2;i>=0;i--){\n suff[i] =suff[i+1]| arr[i];\n }\n \n for(int i=0;i<n;i++){\n if(i==0){\n ll xx = suff[1];\n ll yy = arr[i] * pow(2,k);\n xx|=yy;\n ans = max(ans,xx); \n }\n else if(i==n-1){\n ll xx = pre[n-2];\n ll yy = arr[i] * pow(2,k);\n xx|=yy;\n ans=max(ans,xx);\n }\n else {\n ll xx = pre[i-1];\n ll yy = suff[i+1];\n ll zz = arr[i] * pow(2,k);\n xx = xx | yy | zz;\n ans=max(ans,xx);\n }\n }\n return ans;\n \n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximum-or | Bit Manipulation approach | TC: O(n) | SC: O(1) | Java solution | Clean Code | bit-manipulation-approach-tc-on-sc-o1-ja-5mvf | Intuition\nLet n = nums.length\nLet\'s assume $k = 1$. We can multiply each number by $2$ one-by-one and for each we will calculate nums[0] | nums[1] | ... | nu | vrutik2809 | NORMAL | 2023-06-28T12:55:42.044498+00:00 | 2023-07-01T10:50:53.794004+00:00 | 43 | false | # Intuition\nLet `n = nums.length`\nLet\'s assume $k = 1$. We can multiply each number by $2$ one-by-one and for each we will calculate `nums[0] | nums[1] | ... | nums[n - 1]`. The answer will be maximum among all of this.\nNow let\'s say $k \\gt 1$. For each $k$ we have $n$ choices to pick. But rathar then picking other element, it is always better to pick an element which was giving maximum answer for $k = 1$ and multiply it further for $k - 1$ times and take maximum for answer.\nSo, in general we can multiply each number by $2^k$ one-by-one and for each we will calculate `nums[0] | nums[1] | ... | nums[n - 1]`. The answer will be maximum among all of this.\n\n# Approach\n- Store the total bitcount for each index from $0$ to $63$ in `bits` array. (this array will be used to calculate `nums[0] | nums[1] | ... | nums[n - 1]` in nearly $O(1)$ time)\n- For each `t` in `nums`\n - Remove the actual bitcount of `t` from `bits` array\n - Multiply it by $2$\n - Add the new bitcount in `bits` array. if bitcount at this index is > 0 then add it the `curr` answer\n - Remove the new bitcount and add the actual one to get back to original state\n- Take maximum of `curr` for each `t` \n\n# Complexity\n- Time complexity: $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(1)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n long bits[] = new long[64];\n for(int i = 0;i < nums.length;i++){\n for(int j = 0;j < 64;j++){\n bits[j] += (((long)nums[i] >> j) & 1);\n }\n }\n long max = 0;\n for(int i = 0;i < nums.length;i++){\n long t = nums[i];\n for(int j = 0;j < 64;j++){\n bits[j] -= ((t >> j) & 1); // removing actual bitcount\n }\n t *= (1L << k);\n long curr = 0;\n for(int j = 0;j < 64;j++){\n bits[j] += ((t >> j) & 1); // adding new bitcount\n if(bits[j] > 0) curr |= (1L << j);\n bits[j] -= ((t >> j) & 1); // removing new bitcount\n bits[j] += (((long)nums[i] >> j) & 1); // adding actual bitcount\n }\n max = Math.max(max,curr);\n }\n return max;\n }\n}\n```\n\n# Upvote if you like it \uD83D\uDC4D\uD83D\uDC4D | 1 | 0 | ['Bit Manipulation', 'Java'] | 0 |
maximum-or | Prefix OR | Suffix OR | C++ | prefix-or-suffix-or-c-by-sankalp0109-6ubk | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | sankalp0109 | NORMAL | 2023-05-19T10:02:02.728628+00:00 | 2023-05-19T10:02:02.728663+00:00 | 74 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n long long mul = 1<<k;\n int n = nums.size();\n vector<int> pre(n),suf(n);\n pre[0] = nums[0];\n suf[n-1] = nums[n-1];\n for(int i = 1;i < n;i++){\n pre[i] = nums[i] | pre[i-1];\n suf[n-1-i] = nums[n-i-1] | suf[n-i];\n }\n long long ans = 0;\n long long temp = 0;\n for(int i = 0;i < n;i++){\n temp = mul*nums[i];\n if(i-1 >= 0){\n temp = temp | pre[i-1];\n }\n if(i+1 < n){\n temp = temp | suf[i+1];\n }\n ans = max(temp,ans);\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Array', 'Greedy', 'Bit Manipulation', 'Prefix Sum', 'C++'] | 0 |
maximum-or | Beats 100% | beats-100-by-akdev14-tp4d | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | akdev14 | NORMAL | 2023-05-16T08:08:23.034356+00:00 | 2023-05-16T08:08:23.034388+00:00 | 126 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n int len = nums.length;\n long pre[] = new long[len + 1];\n long suf[] = new long[len + 1];\n long res = 0, pow = 1;\n for(int i = 0; i < k; i++) {\n pow *= 2;\n }\n pre[0] = 0;\n for(int i = 0; i < len; i++) pre[i + 1] = pre[i] | nums[i];\n \n suf[0] = 0;\n for(int i = len - 1; i >= 0; i--) suf[i] = suf[i + 1] | nums[i];\n \n for(int i = 0; i < len; i++) res = Math.max(res, pre[i] | (nums[i] * pow) | suf[i + 1]);\n \n return res;\n }\n}\n``` | 1 | 0 | ['Iterator', 'Java'] | 0 |
maximum-or | Rust/Python. Linear with full math proof (no handwaving, only math) | rustpython-linear-with-full-math-proof-n-96hg | Math proof\n\nHere by the size of number I mean a lengh of its binary representation. For example 1011101 has size of 7.\n\nLets assume that we have an array of | salvadordali | NORMAL | 2023-05-15T19:46:03.143350+00:00 | 2023-05-15T19:46:03.143386+00:00 | 150 | false | # Math proof\n\nHere by the size of number I mean a lengh of its binary representation. For example `1011101` has size of `7`.\n\nLets assume that we have an array of numbers where one number has the size of `n` and all other numbers have the size of at most `n - 1`. And now we have `k` operations. Here I will prove that the best way to use them is to apply them all to the number of size `n`.\n\nTo prove this let\'s see \n 1. What is the minimum number we can achieve by applying k operations to max size number.\n 2. What is the maximum or of numbers we can achive by applying k to other numbers\n 3. Show that 1 > 2\n\n**1)** It will be $2^{n + k}$ (if we assume that our max-size number is one with all zeroes).\n**2)** We can see that the maximum will be achived if all other numbers consist of only ones. So `111..1` where the number of ones is `n-1` which is $2^{n} - 1$. No matter what we do, with our `k` operations we can\'t achieve the or of all numbers higher than $2^{n + k} - 1$\n**3)** So it is clear that 1 > 2 and therefore we proved that in this case we need to apply all operations to max-size value.\n\nNow lets assume that there are `x` elements of max-size and `y` elements of of smaller size. It is easy to see that you should not use any operations on smaller size elements. This is because if you used even only one operation on smaller size element, you end up with `x+1` max-size elements and `y-1` smaller size elements but have left `k-1` operations.\n\nSo we end up with a situation where we have `k` operations and all number of the same size $n$ and need to decided how we should use those operations. And similar to beginning proof we can show that the minimum number that we can achieve by applying all operations to one number is $2^{n + k}$ and the maximum number in all other cases are $2^{n + k} - 1$\n\n\n\n# Solution\n\nSo we showed that we need to find which number we need to multiply by $2^k$ to get the maximum or. How can we efficiently do this? For example if we want to efficintly multiply k-th number.\n\n$A_0, ... A_{k-1}, A_k, A_{k+1}, ... A_n$\n\nThe answer will be `prefix_or[A[0..k-1]] | (A[k] * 2^k) | suffix_or[A[k+1..n]]`\n\nSo this can be done in $O(1)$ for every element, by precomputing `prefix_or` and `suffix_or`.\n\n# Complexity\n\nWe iterate over an array 3 times and use 2 additional arrays.\n\n- Time complexity: $O(n)$\n- Space complexity: $O(n)$\n\n# Code\n\n```Rust []\nimpl Solution {\n pub fn maximum_or(nums: Vec<i32>, k: i32) -> i64 {\n let (mult, n) = (1 << k as u64, nums.len());\n let mut prefix_or = vec![0; n + 1];\n for i in 0 .. n {\n prefix_or[i + 1] = prefix_or[i] | nums[i] as u64;\n }\n\n let mut suffix_or = vec![0; n + 1];\n for i in (0 .. n).rev() {\n suffix_or[i] = suffix_or[i + 1] | nums[i] as u64;\n }\n\n let mut res = 0;\n for i in 0 .. n {\n res = res.max(prefix_or[i] | suffix_or[i + 1] | (nums[i] as u64 * mult));\n }\n return res as i64;\n }\n}\n```\n```python []\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n mult, n = 1 << k, len(nums)\n\n prefix_or = [0] * (n + 1)\n for i in range(n):\n prefix_or[i + 1] = prefix_or[i] | nums[i]\n \n suffix_or = [0] * (n + 1)\n for i in range(n - 1, -1, -1):\n suffix_or[i] = suffix_or[i + 1] | nums[i]\n\n res = 0\n for i in range(n):\n res = max(res, prefix_or[i] | suffix_or[i + 1] | (nums[i] * mult))\n return res\n```\n | 1 | 0 | ['Python', 'Rust'] | 1 |
maximum-or | Easy prefix and suffix approach ✅ || Beats 88% | easy-prefix-and-suffix-approach-beats-88-06am | \n# Complexity\n- Time complexity: O(N)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(N)\n Add your space complexity here, e.g. O(n) \n\n | neergx | NORMAL | 2023-05-14T09:41:44.430979+00:00 | 2023-05-14T09:41:44.431024+00:00 | 36 | false | \n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n \n long long maximumOr(vector<int>& nums, int k) {\n int n = nums.size();\n long long ans = 0;\n vector<long long> prefix(n+1, 0);\n vector<long long> suffix(n+1, 0);\n long long temp = 1 << k;\n \n for(int i = 0; i < n; i++){\n prefix[i+1] = nums[i] | prefix[i];\n }\n for(int i = n-1; i >= 0; i--){\n suffix[i] = nums[i] | suffix[i+1];\n }\n \n for(int i = 0; i < n; i++){\n ans = max((prefix[i] | suffix[i+1] | temp*nums[i]), ans);\n }\n return ans;\n\n }\n};\n``` | 1 | 0 | ['Bit Manipulation', 'Suffix Array', 'Prefix Sum', 'C++'] | 0 |
maximum-or | Python | Prefix | Suffix | python-prefix-suffix-by-dinar-omv0 | I checked several solutions and created my own to see if I understood them correctly.\nThe idea is here to find number with the highest bit_length and save the | dinar | NORMAL | 2023-05-13T23:12:04.366627+00:00 | 2023-05-13T23:12:04.366657+00:00 | 78 | false | I checked several solutions and created my own to see if I understood them correctly.\nThe idea is here to find number with the highest `bit_length` and save the value at `max_bit` and numbers at `max_bit_list`. Meanwhile also find bitwise OR for all other numbers ans keep them in `ans`.\nBecuase we want the maximum bitwise OR we want to shift left numbers `k` times. Thus we shift every numbers from `max_bit_list` and keep total maximum of OR operation.\n\n```\nfrom operator import ior\n\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n \n max_bit = 0\n max_bit_list = []\n ans = 0\n for n in nums:\n n_bits = n.bit_length()\n if n_bits > max_bit:\n max_bit_list.append(ans)\n ans = reduce(ior, max_bit_list)\n max_bit_list = [n,]\n max_bit = n_bits\n elif n_bits == max_bit:\n max_bit_list.append(n)\n else:\n ans |= n\n \n prefix = [0] * (len(max_bit_list))\n suffix = [0] * (len(max_bit_list))\n \n for i in range(1, len(max_bit_list)):\n prefix[i] = prefix[i - 1] | max_bit_list[i - 1]\n \n for i in range(len(max_bit_list) - 1, 0, -1):\n suffix[i - 1] = suffix[i] | max_bit_list[i]\n\n ans2 = 0\n \n for i in range(len(max_bit_list)):\n ans2 = max(ans2, ans | prefix[i] | max_bit_list[i] << k | suffix[i])\n \n return ans2\n``` | 1 | 0 | ['Python'] | 0 |
maximum-or | Easiest Dynamic Programming solution | |C++ | easiest-dynamic-programming-solution-c-b-k6ys | What you have to do is basically check if all different combinations of number when multiplied with 2 give the maximum bitwise OR or they do not.\nSimple knaps | shashankyadava08 | NORMAL | 2023-05-13T21:34:20.811099+00:00 | 2023-05-13T21:34:58.341798+00:00 | 107 | false | What you have to do is basically check if all different combinations of number when multiplied with 2 give the maximum bitwise OR or they do not.\nSimple knapsack solution.\nTime Complexity is (K* K* N)\nSpace Complexity is (K*N)\n```\nclass Solution {\npublic:\n long long dp[100005][16];\n long long recur(vector<int> &nums,int k,int index){\n if(index==nums.size())return 0;\n if(dp[index][k]!=-1)return dp[index][k];\n long long count = 1;\n long long maxx = 0;\n for(int i = 0; i<=k; i++){\n maxx = max(maxx,(nums[index]*count)|recur(nums,k-i,index+1));\n count*=2;\n }\n return dp[index][k] = maxx;\n }\n long long maximumOr(vector<int>& nums, int k) {\n memset(dp,-1,sizeof(dp));\n return recur(nums,k,0);\n }\n};\n``` | 1 | 0 | ['Dynamic Programming', 'Recursion', 'Memoization'] | 1 |
maximum-or | [Python3] Two Counters, Constant Space, Lots of Bit Hacks | python3-two-counters-constant-space-lots-g18p | Disclaimer\nI wasn\'t able to crack this question during the contest; I figured out the trick but wasn\'t able to implement it nor rigorously prove why it works | wlui | NORMAL | 2023-05-13T21:03:26.510762+00:00 | 2023-05-13T21:04:14.409738+00:00 | 25 | false | # Disclaimer\nI wasn\'t able to crack this question during the contest; I figured out the trick but wasn\'t able to implement it nor rigorously prove why it works. Other solutions do a good job with the proof so I\'ll just explain my intuition down below.\n\n# Trick\nWe want to find the maximal array OR (`nums[0] | nums[1] | ... | nums[n - 1]`), where we can multiply by 2 any values (possibly different ones) in the array, for a total of k multiplications. Immediately, because we\'re multiplying by 2 and trying to maximize a bitwise operation, we should realize that multiplying by 2 is equivalent to a single left shift.\n\nIt also turns out that it\'s best to select only one value to be shifted k times. This makes sense because, by shifting say the largest value k times, we can achieve a really big single value to be used in our array OR operation. However, choosing the maximum value in the array doesn\'t necessarily work (see the given example [12, 9]).\n\n# Algorithm\nA correct algorthm will do the following:\n1. Figure out the candidates to be shifted (one pass)\n2. For each number in the array (second pass)\n a. If the number is a candidate, do the below\n b. Compute the OR of the array, discluding the candidate; `curr_removed`\n c. Compute the candidate, shifted left `k` times; `shifted`\n d. Set the result to be the larger between the result and `shifted | curr_removed`\n\nYou\'ll notice that this approach would run in quadratic time since we\'re recomputing the array OR not including the candidate each time. Because the same bit can be included multiple times, we need to be smart about this, which is explained in the implementation.\n\n# Implementation + Bithacks\nSince we need to compute the array OR quickly and need only to simulate removing a single candidate, it makes sense to precompute this in a single pass for constant lookup later. However, it\'s not entirely clear exactly how to remove a candidate from an array OR from a first glance. If we re-think the array OR, we\'ll notice that it\'s equal to an OR of two components:\n\n`array OR = bits_appearing_exactly_once | bits_appearing_two_or_more_times`\n\nSo, in our first pass that computes the candidates to be shifted, we can also compute the two bitsets as well (`once` and `two_or_more`).\n\nNote that calculating the above bitsets can be done using only bit operations in an iterative way, for each number `curr = nums[i]`. Note that the order of how we\'re calculating `two_or_more` and `once` matters.\n\n`two_or_more = two_or_more | (once & curr)`.\n- Doing `two_or_more | ...` indicates we\'re keeping the current bits set two or more times, as desired.\n- `once & curr` keeps bits that have appeared exactly once and are present in `curr`, which is equal to the bits that appear exactly twice within `curr`.\n\n`once = ~two_or_more & (once | curr)`\n- `~two_or_more & ...` means that we\'re using our updated `two_or_more` and making it so that any bits that are set in it **are cleared** in our computation of `once`\n- `once | curr` simply tracks bits that had appeared once and possibly new bits present in `curr`.\n\nWith `once` and `two_or_more` computed, simulating the removal of a candidate from the array OR is more straightforward:\n`array OR with candidate shifted = two_or_more | (once & ~curr) | (curr << k)`\n- The bits in `two_or_more` are kept because removing of the bits in `curr` wouldn\'t have affected the presence of these bits when calculating the rest of the array OR\n- `once & ~curr` keeps the bits appearing once while also simulating the removal of the bits set in `curr`\n- `curr << k` left shifts `curr` the required number of times.\n\n# Code\n```\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n # maximumOr calculation: the best result should be the maximal value of:\n # OR(nums[i], i != j) | nums[j] << k, for each j. Not too sure why.\n # Compute bit counts efficiently in first pass \n once, two_or_more = 0, 0 # track bits appearing exactly one time, bits appearing two+ times\n highest_bit = 0 # only need to promote the numbers with the highest bit set\n for curr in nums:\n highest_bit = max(highest_bit, curr.bit_length()) # track highest bit set using built-in bit_length\n two_or_more_next = two_or_more | ( # keep current two or more\n once & curr\n )\n two_or_more = two_or_more_next # things that have appeared 2+ times updated \n once_next = ~two_or_more & ( # zero out things appearing two/more times using updated two/more\n once | # things that have appeared once are kept\n curr # curr in binary = things that have appeared once\n )\n\n once = once_next\n\n # maximumOr calculation\n res = 0\n for curr in nums:\n if curr.bit_length() != highest_bit: # not a candidate for promotion\n continue\n shifted = curr << k\n curr_removed = once & ~curr # clear curr from once\n cand = two_or_more | shifted | curr_removed\n res = max(res, cand)\n\n return res\n``` | 1 | 0 | ['Python3'] | 0 |
maximum-or | O(45N) simple | o45n-simple-by-dkravitz78-dk67 | Make an array counting how many times each bit is in a number.\nThen simply loop through each number n and compute what would happen if we doubled it k times. \ | dkravitz78 | NORMAL | 2023-05-13T20:20:37.749093+00:00 | 2023-05-13T20:20:37.749132+00:00 | 69 | false | Make an array counting how many times each bit is in a number.\nThen simply loop through each number n and compute what would happen if we doubled it k times. \nFor each bit i to count, either \n(1) B[i]>1 (will count for sure no matter what is done to n)\n(2) B[i]=1 and (1<<i)&n=0 (changing n won\'t change B[i])\n(3) B[i]=0 but (n<<k)&(1<<i), doubling n k times will make it count.\nSince n goes up to 10^9 which is less than 2^30, and k<=15, we go up to 45. \n```\n def maximumOr(self, nums: List[int], k: int) -> int:\n B = [0 for _ in range(45)]\n \n for n in nums:\n for i in range(30):\n\t\t\t if (1<<i)&n: B[i]+=1\n \n ret = 0\n for n in nums: \n Sn = 0\n for i in range(45):\n if B[i]>1: Sn+=(1<<i)\n elif B[i]==1 and (1<<i)&n==0: Sn+=(1<<i)\n elif (n<<k)&(1<<i): Sn+=(1<<i)\n \n ret = max(ret,Sn)\n return ret\n``` | 1 | 0 | [] | 0 |
maximum-or | Bit-operation, Easy Solution | bit-operation-easy-solution-by-absolute-pfs3r | The key observation is that you should apply all the operations to any one of the element.\nWhy? Any 2^i is greater than the sum of all 2^(0 to i-1)\nor (2^i> | absolute-mess | NORMAL | 2023-05-13T18:59:41.550585+00:00 | 2023-05-13T18:59:41.550632+00:00 | 87 | false | The key observation is that you should apply all the operations to any one of the element.\nWhy? Any 2^i is greater than the sum of all 2^(0 to i-1)\nor (2^i> 2^(i-1)+2^(i-2).....+ 2^0), \nso we will multiply any number k times, so that we get the highest set bit and thus the highest sum.\n\nSolution- We will check for every index by applying all the k operations at that index and then find the max resultant OR.\n\nTime Complexity: O(N * 50)\nSpace Complexity: O(50)\n\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n long long ans=0;\n vector<int> bit(50,0);\n for(auto x:nums) {\n for(int i=0;i<31;i++) {\n if(x&(1<<i)) \n bit[i]++;\n }\n }\n for(auto x:nums) {\n vector<int> temp=bit;\n for(int i=0;i<31;i++) {\n if(x&(1<<i)) \n temp[i+k]++,temp[i]--;\n }\n long long num=0;\n for(auto i=0;i<50;i++) \n if(temp[i]) num+=(1LL<<i);\n if(num>ans) ans=num;\n }\n return ans;\n \n }\n};\n```\nHappy Coding | 1 | 0 | ['Bit Manipulation', 'C'] | 0 |
maximum-or | Easy Solution with SC & TC & Intution | easy-solution-with-sc-tc-intution-by-ms9-9f0y | \n# Intution\n 1. We do k operations on ONE picked element => This is because if a number is picked and a operation is done once it is giving max result , then | MSJi | NORMAL | 2023-05-13T17:32:05.885580+00:00 | 2023-05-13T17:33:11.271525+00:00 | 90 | false | \n# Intution\n 1. We do k operations on ONE picked element => This is because if a number is picked and a operation is done once it is giving max result , then this means doing it k times maximisesour ans (we are left shifing each time)\n2. Why not maximum element picked give correct ans?\n \n ->eg: \n 12: 1 1 0 0\n 9: 1 0 0 1\n \n 24: 1 1 0 0 0 12: 1 1 0 0\n 9: 1 0 0 1 18: 1 0 0 1 0 \n 25 30\n So, In case numbers are in NOT very far from each , we cant pick the the greatest . We have to TRY Each element\n\n# Complexity\n- Time complexity:\n $$O(n)$$ \n\n- Space complexity:\n$$O(n)$$ \n\n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int n = nums.size();\n long long ans = 0,p = 1;\n vector<long long> prefix_or(n,0),suffix_or(n,0);\n\n p = p<<k;\n\n prefix_or[0] = nums[0];\n for(int i=1;i<n;i++){\n prefix_or[i] = prefix_or[i-1]|nums[i];\n }\n suffix_or[n-1] = nums[n-1];\n for(int i=n-2;i>=0;i--){\n suffix_or[i] = suffix_or[i+1]|nums[i];\n }\n\n for(int i=0;i<n;i++){\n long long small_ans = (i>=1?prefix_or[i-1]:0)|(i<=n-2?suffix_or[i+1]:0)|(nums[i]*p);\n ans = max(ans,small_ans);\n }\n\n return ans;\n\n }\n\n};\n``` | 1 | 0 | ['C++'] | 1 |
maximum-or | Prefix OR Current_Element OR Suffix | prefix-or-current_element-or-suffix-by-w-qnr7 | \nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int n=nums.size();\n vector<long long>pOR(n),sOR(n);\n p | whorishi | NORMAL | 2023-05-13T17:24:49.807565+00:00 | 2023-05-13T17:24:49.807608+00:00 | 44 | false | ```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int n=nums.size();\n vector<long long>pOR(n),sOR(n);\n pOR[0]=nums[0];\n sOR[n-1]=nums[n-1];\n \n for(int i=1;i<nums.size();i++)\n {\n pOR[i]=pOR[i-1] | nums[i];\n }\n \n for(int i=n-2;i>=0;i--)\n {\n sOR[i]=sOR[i+1] | nums[i];\n }\n \n long long ans=0;\n int kk;\n for(int i=0;i<n;i++)\n {\n kk=k;\n long long p;\n if(i==0) \n p=0;\n else \n p=pOR[i-1];\n \n long long s;\n if(i==n-1) \n s=0;\n else \n s=sOR[i+1];\n \n long long x=nums[i];\n while(kk--)\n {\n x*=2;\n }\n \n long long cor=p;\n cor = cor | x;\n cor = cor | s;\n ans=max(ans,cor);\n }\n return ans;\n \n }\n};\n```\n\n# ***PLS UPVOTE*** | 1 | 0 | ['Bit Manipulation', 'C', 'Suffix Array'] | 0 |
maximum-or | Easy C++ Solution | easy-c-solution-by-5matuag-fdx3 | \n\n# Code\n\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n long long ans = 0;\n long long aur = 0;\n ve | 5matuag | NORMAL | 2023-05-13T17:07:59.288281+00:00 | 2023-05-13T17:07:59.288326+00:00 | 20 | false | \n\n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n long long ans = 0;\n long long aur = 0;\n vector<int> setbit(34, 0);\n for (int j = 0; j < nums.size(); j++){\n aur |= nums[j];\n int count = 0;\n int temp = nums[j];\n while(temp){\n if(temp % 2){\n setbit[count]++;\n }\n temp /= 2;\n count++;\n }\n }\n for (int i = 0; i < nums.size(); i++){\n long long orr = aur;\n long long x = nums[i] * pow(2, k);\n int count = 0;\n int temp = nums[i];\n while(temp){\n if(temp % 2){\n if(setbit[count] == 1){\n orr ^= (long long)pow(2, count);\n }\n }\n temp /= 2;\n count++;\n }\n orr |= x;\n ans = max(ans, orr);\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximum-or | EASY CPP SOLUTION || USING PREFIX & SUFIX | easy-cpp-solution-using-prefix-sufix-by-tkl5w | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ankit_kumar12345 | NORMAL | 2023-05-13T16:55:53.218247+00:00 | 2023-05-13T16:55:53.218290+00:00 | 137 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\no(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long helper(long long value , int k){\n while(k--){\n value*=(long long) 2;\n }\n return (long long)value;\n }\n long long maximumOr(vector<int>& nums, int k) {\n \n int n = nums.size();\n if(n == 1 ) return helper(nums[0],k);\n \n vector<int>prefix(n);\n vector<int>sufix(n);\n\n prefix[0] = nums[0];\n sufix[n-1] = nums[n-1];\n\n for(int i = 1 ; i<n; i++) \n prefix[i] = (nums[i]) | prefix[i-1];\n \n for(int i = n-2 ; i>= 0 ; i--) \n sufix[i] = (nums[i]) | sufix[i+1];\n \n long long maxi = maxi = (helper(nums[0],k)) | sufix[1];\n maxi = max((helper(nums[n-1],k)) | prefix[n-2] , maxi); \n \n for(int i = 1 ; i< n - 1 ; i++) \n maxi = max(maxi, prefix[i-1] | sufix[i+1] |(helper(nums[i],k)) );\n \n return maxi;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximum-or | EASY C++ SOLUTION ||PREFIX METHOD | easy-c-solution-prefix-method-by-khushie-61d0 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | khushiesharma | NORMAL | 2023-05-13T16:47:39.664534+00:00 | 2023-05-13T16:47:39.664570+00:00 | 26 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->O(n) overall\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->O(n)\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int n=nums.size();\n long long p[n + 1], s[n + 1];\n\xA0\xA0\xA0 long long so, pow = 1;\n\xA0\xA0\xA0\xA0 for (int i = 0; i < k; i++){\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0 pow*=2;\n\xA0\xA0\xA0\xA0 }\n\n\xA0\xA0\xA0 p[0] = 0;\n\xA0\xA0\xA0 for (int i = 0; i < n; i++){\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0 p[i + 1] = p[i] | nums[i];\n\xA0\xA0\xA0 }\n\xA0\xA0\xA0\xA0 s[n] = 0;\n\xA0\xA0\xA0 for (int i = n - 1; i >= 0; i--){\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0 s[i] = s[i + 1] | nums[i];\n\xA0\xA0\xA0 }\n\xA0\xA0\xA0\xA0 so= 0;\n\xA0\xA0\xA0 for (int i = 0; i < n; i++)\n\xA0\xA0\xA0\xA0\xA0\xA0\xA0 so = max(so, p[i] | (nums[i] * pow) | s[i + 1]);\n\n\xA0\xA0\xA0 return so;\n }\n};\n``` | 1 | 0 | ['C++'] | 1 |
maximum-or | Rust Counting the bits | rust-counting-the-bits-by-xiaoping3418-yua5 | Intuition\n Describe your first thoughts on how to solve this problem. \nSince k <= 15, we can only select one number to apply all the operations. \n# Approach\ | xiaoping3418 | NORMAL | 2023-05-13T16:47:38.605446+00:00 | 2023-05-13T17:00:37.961214+00:00 | 50 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince k <= 15, we can only select one number to apply all the operations. \n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nimpl Solution {\n pub fn maximum_or(nums: Vec<i32>, k: i32) -> i64 {\n let mut count= vec![0; 32];\n\n for a in &nums {\n let (mut a, mut i) = (*a, 0);\n while a > 0 {\n count[i] += a % 2;\n a /= 2;\n i += 1;\n }\n }\n\n let mut ret = 0;\n\n for a in nums {\n let mut t = 0;\n for i in 0 .. 32 {\n if count[i] == 0 { continue }\n if count[i] == 1 && a & (1 << i as i64) > 0 { continue }\n t |= 1 << (i as i64);\n }\n t |= ((a as i64) << (k as i64)); \n ret = ret.max(t);\n }\n\n ret\n }\n}\n``` | 1 | 0 | ['Rust'] | 0 |
maximum-or | Prefix OR | prefix-or-by-votrubac-vw96 | I first solved this problem by trying to find the best number to double for each iteration of k.\n\nWrong Answer.\n\nThen I realize that you just need to pick o | votrubac | NORMAL | 2023-05-13T16:45:26.356326+00:00 | 2023-05-13T17:00:43.412581+00:00 | 104 | false | I first solved this problem by trying to find the best number to double for each iteration of `k`.\n\nWrong Answer.\n\nThen I realize that you just need to pick one number and double it `k` times. \n\n**C++**\n```cpp\nlong long maximumOr(vector<int>& nums, int k) {\n vector<int> pref_or{0};\n partial_sum(begin(nums), end(nums), back_inserter(pref_or), bit_or<>());\n long long res = 0, suf_or = 0;\n for (int i = nums.size() - 1; i >= 0; suf_or |= nums[i--])\n res = max(res, pref_or[i] | ((long long)nums[i] << k) | suf_or);\n return res;\n}\n``` | 1 | 1 | ['C'] | 0 |
maximum-or | Prefix and Suffix Array Bitwise Or -Simple and Easy O(n) | prefix-and-suffix-array-bitwise-or-simpl-4ke0 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Lee_fan_Ak_The_Boss | NORMAL | 2023-05-13T16:34:26.686529+00:00 | 2023-05-13T16:34:26.686623+00:00 | 334 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n if len(nums)==1:\n return nums[0]*(2**k)\n sufix = []\n prefix = []\n sufix.append(nums[0])\n prefix.append(nums[-1])\n\n for i in range(1,len(nums)):\n sufix.append(sufix[-1]|nums[i])\n \n for i in range(len(nums)-2,-1,-1):\n prefix.append(prefix[-1]|nums[i])\n prefix = prefix[::-1]\n\n n = 2**k\n res=[]\n for i in range(len(nums)):\n if i == 0:\n res.append(nums[i]*n|prefix[i+1])\n elif i == len(nums)-1:\n res.append(nums[i]*n|sufix[-2])\n else:\n res.append(nums[i]*n|sufix[i-1]|prefix[i+1])\n return max(res)\n``` | 1 | 0 | ['Python', 'C++', 'Java', 'Python3'] | 1 |
maximum-or | C++|Most Easy Intuitive Solution | cmost-easy-intuitive-solution-by-arko-81-91f4 | \nclass Solution {\npublic:\n typedef long long ll;\n long long maximumOr(vector<int>& nums, int k) {\n int n=nums.size();\n vector<int> pre | Arko-816 | NORMAL | 2023-05-13T16:32:48.599915+00:00 | 2023-05-13T16:32:48.599941+00:00 | 57 | false | ```\nclass Solution {\npublic:\n typedef long long ll;\n long long maximumOr(vector<int>& nums, int k) {\n int n=nums.size();\n vector<int> pref(n,0);\n vector<int> suff(n,0);\n pref[0]=nums[0];\n suff[n-1]=nums[n-1];\n for(int i=1;i<n;i++)\n pref[i]=pref[i-1]|nums[i];\n for(int i=n-2;i>=0;i--)\n suff[i]=suff[i+1]|nums[i];\n long long ans=LONG_MIN;\n if(n==1)\n {\n while(k--)\n nums[0]=nums[0]<<1;\n return nums[0];\n }\n ll z1=nums[0];\n ll x1=k;\n while(x1--)\n z1=z1<<1;\n ans=max(ans,z1|suff[1]);\n ll z2=nums[n-1];\n ll x2=k;\n while(x2--)\n z2=z2<<1;\n ans=max(ans,z2|pref[n-2]);\n for(int i=1;i<n-1;i++)\n {\n long long x=k,z=nums[i];\n while(x--)\n z=z<<1;\n ans=max(ans,pref[i-1]|z|suff[i+1]);\n }\n return ans;\n }\n};\n``` | 1 | 0 | [] | 0 |
maximum-or | Prefix and Suffix OR | prefix-and-suffix-or-by-_kitish-ss0n | Code\n\ntypedef long long ll;\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n ll val = 1, n = size(nums);\n for( | _kitish | NORMAL | 2023-05-13T16:21:15.920194+00:00 | 2023-05-13T16:21:15.920227+00:00 | 75 | false | # Code\n```\ntypedef long long ll;\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n ll val = 1, n = size(nums);\n for(int i=1; i<=k; ++i) val *= 2;\n vector<ll> pre(n),suff(n);\n pre[0] = nums[0];\n suff[n-1] = nums[n-1];\n for(int i=1; i<n; ++i) pre[i] = pre[i-1] | nums[i];\n for(int i=n-2; i>=0; --i) suff[i] = suff[i+1] | nums[i];\n ll ans = 0;\n for(int i=0; i<n; ++i){\n ll x = 0;\n if(i>0) x=pre[i-1];\n if(i != n-1) x |= suff[i+1];\n x |= (nums[i]*1ll*val);\n ans = max(ans,x);\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Greedy', 'Suffix Array', 'Prefix Sum', 'Bitmask', 'C++'] | 0 |
maximum-or | C++ | Using Precomputation | c-using-precomputation-by-deepak_2311-7zlh | Complexity\n- Time complexity:O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(n)\n Add your space complexity here, e.g. O(n) \n\n# Code | godmode_2311 | NORMAL | 2023-05-13T16:14:40.304406+00:00 | 2023-05-13T17:13:29.382065+00:00 | 135 | false | # Complexity\n- Time complexity:`O(n)`\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:`O(n)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n \n // check current element is creating maximum OR or not\n long long checkForCurrent(long long curr , int k){\n \n while(k--) curr *= 2;\n \n return curr;\n }\n \n long long maximumOr(vector<int>& nums, int k) {\n \n // input array length\n int n = nums.size();\n \n // result & current OR\n long long max_Or = 0 , curr = 0;\n \n // create prefix OR\n vector<int>pre(n);\n pre[0] = nums[0];\n \n for(int i=1;i<n;i++) pre[i] = pre[i-1] | nums[i];\n \n \n // create suffix OR\n vector<int>suf(n);\n suf[n-1] = nums[n-1];\n \n for(int i=n-2;i>=0;i--) suf[i] = suf[i+1] | nums[i];\n\n \n // if array contains only 1 element\n if(n == 1) return checkForCurrent(nums[0],k);\n \n // check for first element\n curr = checkForCurrent(nums[0],k) | suf[1]; \n max_Or = max(curr,max_Or);\n \n\n // check for last element\n curr = checkForCurrent(nums[n-1],k) | pre[n-2]; \n max_Or = max(curr,max_Or);\n \n // check for remaining element\n for(int i=1;i<n-1;i++){\n \n curr = checkForCurrent(nums[i],k);\n \n curr = suf[i+1] | pre[i-1] | curr;\n max_Or = max(curr,max_Or);\n \n }\n \n // result maximum OR\n return max_Or;\n \n }\n};\n``` | 1 | 0 | ['Array', 'Bit Manipulation', 'Suffix Array', 'Prefix Sum', 'C++'] | 0 |
maximum-or | Greedy | Java | greedy-java-by-viatsevskyi-9vr3 | \nDue to problem constraints, the best strategy is to select a single number from the array and shift it by K. To achieve this efficiently, we should precompute | viatsevskyi | NORMAL | 2023-05-13T16:05:25.394198+00:00 | 2023-05-13T16:18:33.538958+00:00 | 29 | false | \nDue to problem constraints, **the best strategy is to select a single number from the array and shift it by K.** To achieve this efficiently, we should precompute the array\'s results without any shifts. For each element, we subtract it from the precomputed result and apply a K-shift using the bitwise OR operation to update the result. However, one issue arises since the bitwise OR operation is a destructive operation, and we cannot reverse it for a single number. Therefore, we need to manually perform bit counting by utilizing the update method.\n\n```\nclass Solution {\n void update(int[] bits, int n, int op) {\n for (int i = 0; i < bits.length; ++i) {\n if ((n & (1 L << i)) != 0) {\n bits[i] += op;\n }\n }\n }\n\n int toInt(int[] bits) {\n int r = 0;\n for (int i = 0; i < bits.length; ++i) {\n if (bits[i] > 0) {\n r |= 1 << i;\n }\n }\n return r;\n }\n\n public long maximumOr(int[] nums, int k) {\n int[] bits = new int[32];\n for (int n: nums) {\n update(bits, n, 1);\n }\n long r = toInt(bits);\n for (int n: nums) {\n update(bits, n, -1);\n long m = toInt(bits);\n m |= (long) n << k;\n r = Math.max(r, m);\n update(bits, n, 1);\n }\n return r;\n }\n}\n``` | 1 | 1 | [] | 0 |
maximum-or | Prefix and suffix arrays | prefix-and-suffix-arrays-by-_srahul-sv18 | Intuition\n1. Make a Prefix OR & Suffix OR array.\n2. Now try to traverse the array and maximise the \nprefix[i-1] | nums[i]*2^k | suffix[i+1],\n\nthat means fo | _srahul_ | NORMAL | 2023-05-13T16:05:14.299200+00:00 | 2023-05-13T16:20:03.930722+00:00 | 135 | false | # Intuition\n1. Make a Prefix OR & Suffix OR array.\n2. Now try to traverse the array and maximise the \n```prefix[i-1] | nums[i]*2^k | suffix[i+1]```,\n\nthat means for each ```nums[i]``` we\'re multiplying it with `2^k` ORing it with `prefix[i-1]` and `suffix[i+1]`, and checking if this `nums[i]` is giving us the Maximum Or.\n\n**Solve the 2nd example for better intution.**\n\n\n# Code\n```\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n int n = nums.length;\n \n long[] pref = new long[n], suff = new long[n];\n pref[0] = nums[0]; suff[n-1] = nums[n-1];\n\n for(int i=1; i<n; i++){\n pref[i] = (pref[i-1] | nums[i]);\n }\n \n for(int i=n-2; i>=0; i--){\n suff[i] = (suff[i+1] | nums[i]);\n }\n \n long res = 0, mult = 1 << k;\n //mult = 2^k\n \n for(int i=0; i<n; i++){\n //temp = nums[i]*2^k\n\n long temp = (long) mult * nums[i];\n\n if(i-1 >= 0){\n //temp = temp | pref[i-1];\n temp |= pref[i-1];\n }\n \n if(i+1 < n){\n //temp = temp | suff[i+1];\n temp |= suff[i+1];\n }\n \n res = Math.max(temp, res);\n }\n \n return res;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
maximum-or | O(N) Python3 Using Mask of Unique Bits | on-python3-using-mask-of-unique-bits-by-8haqn | Intuition\nThe solution left-shifts a num k times, since that causes the highest possible bit; however, it is unclear which num will need to be shifted.\n\n# Ap | dumbunny8128 | NORMAL | 2023-05-13T16:03:33.156718+00:00 | 2023-05-13T16:08:38.943900+00:00 | 121 | false | # Intuition\nThe solution left-shifts a num k times, since that causes the highest possible bit; however, it is unclear which num will need to be shifted.\n\n# Approach\nWe will check each num to see which num produces the maximum orred value. Prior to iteration, we calculate uniqueMask, the OR of bits that are set in exactly one num, in order to see which bits are removed by shifting any given num. The value produced is the orred nums, adjusted by the bits most by shifting num.\n\n# Complexity\n- Time complexity:\n$$O(N)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution:\n\n def maximumOr(self, nums: List[int], k: int) -> int:\n counts = [0] * 32\n orredNums = 0\n for num in nums:\n orredNums |= num\n bit = 0\n while num:\n if num % 2 == 1:\n counts[bit] += 1\n num //= 2\n bit += 1\n \n # Get the OR of all bits that are in only one num.\n uniqueMask = 0\n for i, count in enumerate(counts):\n if count == 1:\n uniqueMask |= 1 << i\n \n # The best value is produced by left-shifting a num k times.\n # The left-shifting will remove any bits that num had uniquely\n # added, so remove these first.\n bestOrredNumsWithShifts = 0\n for num in nums:\n orredNumsWithShifts = orredNums - (num & uniqueMask)\n orredNumsWithShifts |= num << k\n bestOrredNumsWithShifts = max(\n bestOrredNumsWithShifts, orredNumsWithShifts)\n\n return bestOrredNumsWithShifts\n \n \n``` | 1 | 1 | ['Python3'] | 0 |
maximum-or | Prefix and suffix array in python. | prefix-and-suffix-array-in-python-by-rya-ueek | Approach\nFor every num in the nums array, we will multiply num by 2^k, and keep a track of the bitwise OR of all the array elements taken together. To perform | ryan-gang | NORMAL | 2023-05-13T16:03:15.642476+00:00 | 2023-05-13T16:04:12.092686+00:00 | 307 | false | # Approach\nFor every num in the nums array, we will multiply num by 2^k, and keep a track of the bitwise OR of all the array elements taken together. To perform this computation optimally, we keep a prefix and a suffix array.\n `prefix[i] = bitwise OR of elements at index 0 to i-1.`\n `suffix[i] = bitwise OR of elements at index i+1 to n-1.`\n\nThe reason why we are multiplying a single element by 2^k instead of multiple elements is simple. If we spread out the k over multiple elements, our max OR will not be multiplied by the most optimal multiplicative factor that it could have been. \n\n# Complexity\n- Time complexity: O(N)\n\n- Space complexity: O(N)\n\n# Code\n```\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int: \n pre = [0]\n or_val = 0\n for num in nums:\n or_val |= num\n pre.append(or_val)\n pre.pop()\n\n suf = [0]\n or_val = 0\n for idx in range(len(nums) - 1, -1, -1):\n num = nums[idx]\n or_val |= num\n suf.append(or_val)\n suf.pop()\n suf.reverse()\n\n max_or = 0\n for idx in range(len(nums)):\n num = nums[idx] << k\n prefix = pre[idx]\n suffix = suf[idx]\n\n max_or = max(max_or, num | prefix | suffix)\n\n return (max_or)\n\n``` | 1 | 0 | ['Greedy', 'Suffix Array', 'Prefix Sum', 'Python', 'Python3'] | 0 |
maximum-or | Easy to Understand Solution | Prefix | Suffix | easy-to-understand-solution-prefix-suffi-un7l | \n#define ll long long\nclass Solution {\npublic:\n ll mypow(ll a, ll b) {\nll res = 1;\nwhile (b > 0) {\nif (b & 1)\nres = res * a*1ll;\na = a * a*1ll;\nb > | Sankalp_Sharma_29 | NORMAL | 2023-05-13T16:03:12.879732+00:00 | 2023-05-13T16:03:12.879784+00:00 | 30 | false | ```\n#define ll long long\nclass Solution {\npublic:\n ll mypow(ll a, ll b) {\nll res = 1;\nwhile (b > 0) {\nif (b & 1)\nres = res * a*1ll;\na = a * a*1ll;\nb >>= 1;\n}\nreturn res;\n}\n long long maximumOr(vector<int>& nums, int k) {\n int n=nums.size();\n ll x=0;\n if(n==1) return 1ll*nums[0]*mypow(2,k);\n vector<ll> pre(n,0),suf(n,0);\n for(int i=0;i<n;i++)\n {\n \n if(i==0)\n pre[i]=nums[i];\n else\n pre[i]=pre[i-1]|nums[i];\n }\n for(int i=n-1;i>=0;i--)\n {\n if(i==n-1)\n suf[i]=nums[i];\n else\n suf[i]=suf[i+1]|nums[i];\n }\n ll ans=0;\n for(int i=0;i<n;i++)\n {\n ll x=1ll*nums[i]*1ll*mypow(2,k);\n if(i==0)\n {\n ans=max(ans,x|suf[i+1]);\n }\n else if(i==n-1)\n {\n ans=max(ans,x|pre[i-1]);\n }\n else\n {\n ans=max(ans,x|pre[i-1]|suf[i+1]);\n }\n }\n return ans; \n \n }\n};\n``` | 1 | 0 | [] | 0 |
maximum-or | [Python 3] Prefix Suffix | python-3-prefix-suffix-by-0xabhishek-2apg | \nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n bitwiseOr = lambda x, y: x | y\n \n forward = list(accumulate | 0xAbhishek | NORMAL | 2023-05-13T16:00:57.876540+00:00 | 2023-05-13T16:02:52.367382+00:00 | 456 | false | ```\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n bitwiseOr = lambda x, y: x | y\n \n forward = list(accumulate(nums, bitwiseOr))\n backward = list(accumulate(nums[ : : -1], bitwiseOr))[ : : -1]\n \n forward = [0] + forward[ : -1]\n backward = backward[1 : ] + [0]\n \n res = 0\n \n for i in range(len(nums)):\n total = forward[i] | backward[i]\n t = nums[i] * pow(2, k)\n \n res = max(res, total | t)\n \n return res\n``` | 1 | 0 | ['Bit Manipulation', 'Prefix Sum', 'Python', 'Python3'] | 1 |
maximum-or | EASY C++ SOLUTION || BEGINNER FRIENDLY || EASY TO UNDERSTAND | easy-c-solution-beginner-friendly-easy-t-inn6 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | suraj_kumar_rock | NORMAL | 2025-04-08T23:38:56.955273+00:00 | 2025-04-08T23:38:56.955273+00:00 | 1 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
long long maximumOr(vector<int>& nums, int k) {
int n = nums.size();
long long answer = 0;
long long curr = 0;
vector<long long>prefix(n, 0);
vector<long long>suffix(n, 0);
for(int i =0; i<n; i++)
{
curr |= nums[i];
prefix[i] = curr;
}
curr = 0;
for(int i=n-1; i>=0; i--)
{
curr |= nums[i];
suffix[i] = curr;
}
for(int i=0; i<n; i++)
{
long long curr_val = pow(2, k);
// cout<<curr_val<<" ";
curr_val = nums[i]*curr_val;
curr_val = curr_val | ((i-1 >= 0)? prefix[i-1]:0);
curr_val = curr_val | ((i+1 < n)? suffix[i+1]:0);
answer = max(answer, curr_val);
}
return answer;
}
};
``` | 0 | 0 | ['Array', 'Greedy', 'Bit Manipulation', 'Prefix Sum', 'C++'] | 0 |
maximum-or | DP+Slide Window | dpslide-window-by-linda2024-auoa | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | linda2024 | NORMAL | 2025-03-26T19:00:08.846379+00:00 | 2025-03-26T19:00:08.846379+00:00 | 1 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```csharp []
public class Solution {
public long MaximumOr(int[] nums, int k) {
int len = nums.Length;
long[] leftOr = new long[len], rightOr = new long[len];
long maxOr = 0;
for(int i = 1; i < len; i++)
{
leftOr[i] = leftOr[i-1]|nums[i-1];
}
for(int i = len-2; i >= 0; i--)
{
rightOr[i] = rightOr[i+1]|nums[i+1];
}
int times = (int)Math.Pow(2, k);
for(int i = 0; i < len; i++)
{
long cur = (long)nums[i]*times;
cur |= leftOr[i];
cur |= rightOr[i];
// Console.WriteLine($"{i}th, cur is {cur}, leftOr is {leftOr[i]}, rightOr is {rightOr[i]}");
maxOr = Math.Max(maxOr, cur);
}
return maxOr;
}
}
``` | 0 | 0 | ['C#'] | 0 |
maximum-or | Easy Python Solution | easy-python-solution-by-vidhyarthisunav-v2rv | IntuitionWe compute the prefix OR and suffix OR for the array, then iterate through each element, applying k operations to maximize the result.The above strateg | vidhyarthisunav | NORMAL | 2025-02-18T09:55:47.896343+00:00 | 2025-02-18T09:55:47.896343+00:00 | 2 | false | # Intuition
We compute the prefix OR and suffix OR for the array, then iterate through each element, applying k operations to maximize the result.
The above strategy kicks in through the fact that the optimal approach is to apply all k operations to a single number (why?).
# Code
```python3 []
class Solution:
def maximumOr(self, nums: List[int], k: int) -> int:
n = len(nums)
if n == 1:
return nums[0] * (2 ** k)
pre, suf = [0] * n, [0] * n
pre[0], suf[n - 1] = nums[0], nums[n - 1]
for i in range(1, n):
pre[i] = nums[i] | pre[i - 1]
for i in range(n - 2, -1, -1):
suf[i] = nums[i] | suf[i + 1]
res = -inf
for i in range(n):
new_num = nums[i] * (2 ** k)
if i == 0:
res = max(res, new_num | suf[i + 1])
elif i == n - 1:
res = max(res, new_num | pre[i - 1])
else:
res = max(res, pre[i - 1] | new_num | suf[i + 1])
return res
``` | 0 | 0 | ['Python3'] | 0 |
maximum-or | Max OR || C++ || Explanation for optimal result | max-or-c-explanation-for-optimal-result-qznc9 | IntuitionLeft shift the index since it is multiplied by 2.ApproachThe most optimal approach is to precompute the prefix and suffix or of the vector for each ind | Aditi_71 | NORMAL | 2025-01-30T12:07:54.273300+00:00 | 2025-01-30T12:07:54.273300+00:00 | 6 | false | # Intuition
Left shift the index since it is multiplied by 2.
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
The most optimal approach is to precompute the prefix and suffix or of the vector for each index. Performing k operations on the same value will give maximum result. So the index whose set bit is farthest when left shifted more k times will provide the best output.
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:O(N)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:O(N)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
long long maximumOr(vector<int>& nums, int k) {
long long max_or = 0;
int n = nums.size();
vector<int>prefix(n+1), suffix(n+1);
for(int i=1;i<n;i++){
prefix[i] = prefix[i - 1] | nums[i - 1];
suffix[n-1-i] = suffix[n - i] | nums[n - i];
}
for(int i=0;i<n;i++){
max_or = max(max_or, prefix[i] | ((long long)nums[i] << k) | suffix[i]);
}
return max_or;
}
};
``` | 0 | 0 | ['Bit Manipulation', 'Prefix Sum', 'C++'] | 0 |
maximum-or | JavaScript (nothing new, just use bigint) | javascript-nothing-new-just-use-bigint-b-jxi9 | ApproachReally the same as other solutions out there, but if you dont understand why your solution doesnt work it might be because of the 'number' primitive not | thom-gg | NORMAL | 2025-01-19T10:43:49.072206+00:00 | 2025-01-19T10:43:49.072206+00:00 | 9 | false |
# Approach
Really the same as other solutions out there, but if you dont understand why your solution doesnt work it might be because of the 'number' primitive not being able to properly deal with huge numbers, so use BigInt
# Code
```typescript []
function maximumOr(nums: number[], k: number): number {
// precompute arrays that store the bitwise sum excluding index i
let bitwiseBefore = [];
for (let i = 0; i<nums.length; i++) {
if (i == 0) {
bitwiseBefore.push(0);
}
else {
bitwiseBefore.push(bitwiseBefore[i-1] | nums[i-1]);
}
}
let bitwiseAfter = Array(nums.length).fill(0);
for (let i = nums.length-1; i>= 0; i--) {
if (i == nums.length-1) {
continue;
}
else {
bitwiseAfter[i] = bitwiseAfter[i+1] | nums[i+1];
}
}
let power = BigInt(1);
for (let i = 0; i<k; i++) {
power = power * BigInt(2);
}
let maxValue = BigInt(0);
for (let j = 0; j<nums.length; j++) {
let val = BigInt(nums[j]) * power;
let orSum = BigInt(bitwiseBefore[j]) | val | BigInt(bitwiseAfter[j]);
if (orSum > maxValue) {
maxValue = orSum;
}
}
return Number(maxValue);
};
``` | 0 | 0 | ['TypeScript', 'JavaScript'] | 0 |
maximum-or | 2680. Maximum OR | 2680-maximum-or-by-g8xd0qpqty-zltw | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | G8xd0QPqTy | NORMAL | 2025-01-19T07:01:55.110607+00:00 | 2025-01-19T07:01:55.110607+00:00 | 6 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def maximumOr(self, A: List[int], k: int) -> int:
max_result, left_accum, n = 0, 0, len(A)
right_accum = [0] * n
for i in range(n - 2, -1, -1):
right_accum[i] = right_accum[i + 1] | A[i + 1]
for i in range(n):
max_result = max(max_result, left_accum | (A[i] << k) | right_accum[i])
left_accum |= A[i]
return max_result
``` | 0 | 0 | ['Python3'] | 0 |
maximum-or | Go right, go left, go right | go-right-go-left-go-right-by-j22qidyza7-z5eg | Code | J22qIDYZa7 | NORMAL | 2024-12-25T04:07:44.049562+00:00 | 2024-12-25T04:07:44.049562+00:00 | 1 | false | # Code
```php []
class Solution
{
/**
* @param Integer[] $nums
* @param Integer $k
* @return Integer
*/
function maximumOr($nums, $k)
{
$len = count($nums);
$temp = array_fill(0, $len, 0);
$sum = 0;
for ($i = 0; $i < $len; $i++) {
$temp[$i] |= $sum;
$sum |= $nums[$i];
}
$sum = 0;
for ($i = $len - 1; $i >= 0; $i--) {
$temp[$i] |= $sum;
$sum |= $nums[$i];
}
$result = 0;
foreach ($nums as $key => $num) {
$check = $num << $k;
$check |= $temp[$key];
if($check > $result){
$result = $check;
}
}
return $result;
}
}
``` | 0 | 0 | ['PHP'] | 0 |
maximum-or | ❄ Easy Java Solution❄Beats 100% of Java Users . | easy-java-solutionbeats-100-of-java-user-xbza | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | zzzz9 | NORMAL | 2024-11-27T16:15:20.258655+00:00 | 2024-11-27T16:15:39.472255+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public long maximumOr(int[] a, int k) {\n int n = a.length;\n if( n == 1 ){\n long e = a[0] ; \n return e << k ; \n }\n int[] r = new int[n] ; \n r[n-1] = a[n-1] ; \n for( int i=n-2 ; i>0 ; --i ){\n r[i] |= r[i+1] ; \n r[i] |= a[i] ; \n }\n long e = r[1] ; \n long rs =( e | ( (long) a[0] << k ) ) ; \n long pref = a[0] ; \n for( int i=1 ; i<n-1 ; ++i ){\n rs = Math.max( rs , ( pref | r[i+1] | ( (long) a[i] << k))) ; \n pref |= a[i] ; \n }\n rs = Math.max( rs , pref|( (long) a[n-1] << k ) ) ; \n return rs ; \n }\n}\n\n``` | 0 | 0 | ['Array', 'Greedy', 'Bit Manipulation', 'Prefix Sum', 'Java'] | 0 |
maximum-or | scala oneliner | scala-oneliner-by-vititov-awjr | scala []\nobject Solution {\n def maximumOr(nums: Array[Int], k: Int): Long =\n (nums.iterator zip (\n nums.toList.scanLeft(0)(_ | _).init \n zip | vititov | NORMAL | 2024-10-31T21:07:18.326566+00:00 | 2024-10-31T21:07:18.326598+00:00 | 0 | false | ```scala []\nobject Solution {\n def maximumOr(nums: Array[Int], k: Int): Long =\n (nums.iterator zip (\n nums.toList.scanLeft(0)(_ | _).init \n zip \n nums.reverseIterator.scanLeft(0)(_ | _).toList.reverse.tail\n ))\n .map{case (num,(p,s)) => (num.toLong<<k)|p|s}.max \n}\n``` | 0 | 0 | ['Scala'] | 0 |
maximum-or | CPP Optimized Solution with 100% better Runtime and Memory | cpp-optimized-solution-with-100-better-r-f5fa | Intuition\nThe best approach would be to shift any one of the numbers by k bits. Our bits can be of three types.\n\n- Appearing in no number\n- Appearing in jus | harsh34vardhan | NORMAL | 2024-10-25T05:51:01.838892+00:00 | 2024-10-25T05:51:01.838917+00:00 | 7 | false | # Intuition\nThe best approach would be to shift any one of the numbers by k bits. Our bits can be of three types.\n\n- Appearing in no number\n- Appearing in just one number\n- Appearing in > 1 numbers\n\nNote that the last type of bits will always be set regardless of our operation.\n\n# Approach\nUse two integers, ```single``` and ```multi``` to track the two types of bits. Any bit unset in ```single``` doesn\'t appear anywhere in our numbers. A set bit in ```single``` denotes a bit appearing only once in the whole list of our numbers. A bit set in ```multi``` means a bit set in more than one number.\n\nThe code which handles this is \n```cpp []\nint single = 0, multi = 0;\n\nfor (int num : nums) {\n for (int j = 1; num; j <<= 1, num >>= 1) {\n if (num & 1) {\n multi |= single & j;\n single |= j; \n }\n }\n}\n```\n\nNow that we have ```single``` and ```multi```, we can move ahead. Note that ```single``` also represents the bitwise-or of the whole list of numbers.\n\nFor each number, we want the effect of shifting it by k bits on the total bitwise-or of all the numbers.\n\nThis is computed by \n\n```cpp []\nsingle & ~num | multi | (long long)num << k\n```\n\nAny bits which were set in single because of them being present in ```num```, we need to unset those, as we are shifting the bits of ```num```. ```single & ~num ``` accomplishes this. Then all the bits in `multi` will anyway be set. Finally, since `num` was shifted `k`, we or with that too.\n\n# Complexity\n- Time complexity:\n`O(n log m)`, where `m` is the greatest element in our list. Other other bit analysis solutions claim `O(n)`, which is wrong as we always need to analyze bits, and that adds `O(log m)`. If we were doing it via prefix and suffix arrays, then yes, the complexity is `O(n)`. But those use up `O(n)` space. \n\n- Space complexity:\n`O(1)`. Trivial to see. All other solutions with a claimed `O(1)` space use a vector to track how many times each bit is set, but that is wasteful, because as far we are concerned, it doesn\'t matter if a bit is set twice or a thousand times, it behaves the same. As said above, there are only 3 types of bits, so using two integers suffices. It also helps with direct calculation of results.\n\n\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int single = 0, multi = 0;\n\n for (int num : nums) {\n for (int j = 1; num; j <<= 1, num >>= 1) {\n if (num & 1) {\n multi |= single & j;\n single |= j; \n }\n }\n }\n\n long long res = 0;\n\n for (int num : nums) res = max(res, single & ~num | multi | (long long)num << k);\n\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-or | Optimized----//////O(n)-Time and Space complexity\\\\\\ | optimized-on-time-and-space-complexity-b-2bj4 | Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co | karthickeyan_S | NORMAL | 2024-10-24T07:28:50.959648+00:00 | 2024-10-24T07:28:50.959683+00:00 | 5 | false | # Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n n = len(nums)\n m = pow(2,k)\n if n==1 : return nums[0]*m\n\n #find prefix and suffix OR in single loop\n\n pre = [nums[0]]*n\n suf = [nums[-1]]*n\n j = n-2\n for i in range(1,n):\n pre[i]=nums[i]|pre[i-1]\n suf[j]=nums[j]|suf[j+1]\n j-=1\n \n \'\'\'initialize ans with applying operation max \n of first 1st or last element\'\'\'\n\n ans = max((nums[0]*m) | suf[1] , (nums[-1]*m) | pre[-2])\n for ind in range(1,n-1):\n ans = max(ans,pre[ind-1]|(nums[ind]*m)|suf[ind+1])\n\n return ans\n\n\n\n\n``` | 0 | 0 | ['Python3'] | 0 |
maximum-or | [Python3] 79ms, beats 100% | python3-79ms-beats-100-by-l12tc3d4r-ireh | Background\nI know this is briefly explained but I want to share this code as it gets better results than other solutions I\'ve seen here (79ms, beats 100% of p | l12tc3d4r | NORMAL | 2024-10-23T16:39:06.327677+00:00 | 2024-10-23T16:41:50.180631+00:00 | 7 | false | # Background\nI know this is briefly explained but I want to share this code as it gets better results than other solutions I\'ve seen here (79ms, beats 100% of people).\nThe code should be relatively understandable, at least after looking at other solutions\n\n# Intuition\nTo solve the problem as quickly as possible we need to be able to OR the entire array as quickly as possible, and not to waste time on values that are too small to be relevant.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nTo start, we find a power of 2 of which smaller values are not even worth checking.\nThen, we want to quickly be able to find the OR of the suffix - the entire array from a specific point onwards.\nAt last, we want to occumulate the OR the same way to find the prefix OR result.\n\n# Complexity\n- Time complexity:\n$$O(n)$$\n\n- Space complexity:\n$$O(n)$$\n\n# Code\n```python3 []\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n result=0\n min_relevant = 2**floor(math.log2(max(nums)))\n\n or_occumulating = 0\n suffix_or = [0]*(len(nums))\n for i in range(len(nums)-1, 0, -1):\n suffix_or[i-1] = or_occumulating = or_occumulating | nums[i]\n or_occumulating = 0\n for i in range(len(nums)):\n if nums[i] >= min_relevant:\n result = max(\n result,\n (nums[i] << k) | or_occumulating | suffix_or[i]\n )\n or_occumulating |= nums[i]\n return result\n``` | 0 | 0 | ['Python3'] | 0 |
maximum-or | 42ms beats 98.87% solve by prefix and suffix | 42ms-beats-9887-solve-by-prefix-and-suff-jyrh | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | albert0909 | NORMAL | 2024-09-18T15:39:31.327865+00:00 | 2024-09-18T15:39:31.327895+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n vector<int> prefix(nums.size() + 1, 0), suffix = prefix;\n for(int i = 0;i < nums.size();i++){\n prefix[i + 1] = prefix[i] | nums[i];\n }\n\n for(int i = nums.size() - 1;i >= 0;i--){\n suffix[i] = suffix[i + 1] | nums[i]; \n }\n\n long long ans = 0;\n for(int i = 0;i < nums.size();i++){\n long long n = nums[i] * pow(2, k);\n ans = max(ans, prefix[i] | suffix[i + 1] | n);\n }\n\n return ans;\n }\n};\n\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n``` | 0 | 0 | ['Array', 'Greedy', 'Bit Manipulation', 'Suffix Array', 'Prefix Sum', 'C++'] | 0 |
maximum-or | Prefix + Suffix Sum & Greedy | prefix-suffix-sum-greedy-by-alexpg-w7df | With bit OR operation we will collect all unique bits in array. When we multiple any number by 2 we shifts all bits to the right by 1. The most benefiting bit b | AlexPG | NORMAL | 2024-09-01T11:00:59.124328+00:00 | 2024-09-01T11:00:59.124358+00:00 | 5 | false | With bit OR operation we will collect all unique bits in array. When we multiple any number by 2 we shifts all bits to the right by 1. The most benefiting bit by shifting is the most significant bit in overall OR result. If we shift that bit to the right by 1 it will have even more significant power. From that observation we can understand that we need to shift number with most significant bit for k times to the right. However there could be few different numbers with most significant bits and it is not mandatory that shifting highest number will benefit more than other numbers with same most significant bits. For example, lets assume that we have total OR of array as 110011 and we have 2 numbers with most significant bits: 100001 and 100010. If our k = 2 then after shifting first number we would have 10111110 and after shifting second number we would have 10111101. In that case 10111110 > 10111101 while 100001 < 100010. Thats why we need to calculate all possible values after shifting each number and select highest one.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int prefix = 0;\n // We need precompute all suffixes as bit OR is irreversible operation\n // However prefix we can compute as we go on\n vector<int> suffix(nums.size()+1);\n for (int i = nums.size(); i > 0; i--)\n suffix[i-1] = suffix[i] | nums[i-1];\n\n long long res = 0;\n for (int i = 0; i < nums.size(); i++) {\n long long val = nums[i];\n // Calculate value with current number shifted by K\n val = (val << k) | prefix | suffix[i+1];\n res = max(res, val);\n // Update prefix\n prefix |= nums[i];\n }\n return res;\n }\n};\n\nauto init = []() {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n cout.tie(nullptr);\n return \'c\';\n}();\n\n``` | 0 | 0 | ['C++'] | 0 |
maximum-or | Prefix Suffix OR || Super Simple || C++ | prefix-suffix-or-super-simple-c-by-lotus-6xjd | Code\n\nclass Solution \n{\npublic:\n long long maximumOr(vector<int>& nums, int k) \n {\n long long n=nums.size();\n vector<long long> prex | lotus18 | NORMAL | 2024-08-17T11:30:13.721683+00:00 | 2024-08-17T11:30:13.721715+00:00 | 2 | false | # Code\n```\nclass Solution \n{\npublic:\n long long maximumOr(vector<int>& nums, int k) \n {\n long long n=nums.size();\n vector<long long> prexor(n,0), sufxor(n,0);\n prexor[0]=nums[0];\n for(long long x=1; x<nums.size(); x++)\n {\n prexor[x]=(prexor[x-1]|nums[x]);\n }\n sufxor[n-1]=nums[n-1];\n for(long long x=n-2; x>=0; x--)\n {\n sufxor[x]=(sufxor[x+1]|nums[x]);\n }\n long long p=pow(2,k);\n long long ans=0;\n for(long long x=0; x<n; x++)\n {\n long long o=nums[x]*p;\n if(x>0) o|=prexor[x-1];\n if(x<n-1) o|=sufxor[x+1];\n ans=max(ans,o);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Bit Manipulation', 'Prefix Sum', 'C++'] | 0 |
maximum-or | Simple Java | (with meme) | simple-java-with-meme-by-arkadeepgr-zqyg | \n# Code\n\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n //Arrays.sort(nums);\n if(nums.length==1)\n return nums[ | arkadeepgr | NORMAL | 2024-08-15T10:43:15.478762+00:00 | 2024-08-15T10:43:15.478790+00:00 | 4 | false | \n# Code\n```\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n //Arrays.sort(nums);\n if(nums.length==1)\n return nums[0]*(int)Math.pow(2,k);\n\n long[] prev = new long[nums.length];\n long[] post = new long[nums.length];\n long res = Integer.MIN_VALUE;\n\n prev[0] = 0;\n prev[1] = nums[0];\n\n post[nums.length-1] = 0;\n post[nums.length-2] = nums[nums.length-1];\n\n for(int i=2;i<nums.length;i++){\n prev[i] = nums[i-1]|prev[i-1];\n } \n for(int i=nums.length-3;i>=0;i--){\n post[i] = nums[i+1]|post[i+1];\n } \n\n for(int i=nums.length-1;i>=0;i--){\n long exc = prev[i] | post[i];\n long self = (long)nums[i]<<k;\n res = Math.max(res,exc | self);\n }\n \n return res;\n }\n\n}\n```\n\n\n | 0 | 0 | ['Java'] | 0 |
maximum-or | Simple Java | (with meme) | simple-java-with-meme-by-arkadeepgr-xhw0 | \n# Code\n\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n //Arrays.sort(nums);\n if(nums.length==1)\n return nums[ | arkadeepgr | NORMAL | 2024-08-15T10:01:23.239015+00:00 | 2024-08-15T10:01:23.239046+00:00 | 7 | false | \n# Code\n```\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n //Arrays.sort(nums);\n if(nums.length==1)\n return nums[0]*(int)Math.pow(2,k);\n\n long[] prev = new long[nums.length];\n long[] post = new long[nums.length];\n long res = Integer.MIN_VALUE;\n\n prev[0] = 0;\n prev[1] = nums[0];\n\n post[nums.length-1] = 0;\n post[nums.length-2] = nums[nums.length-1];\n\n for(int i=2;i<nums.length;i++){\n prev[i] = nums[i-1]|prev[i-1];\n } \n for(int i=nums.length-3;i>=0;i--){\n post[i] = nums[i+1]|post[i+1];\n } \n\n for(int i=nums.length-1;i>=0;i--){\n long exc = prev[i] | post[i];\n long self = (long)nums[i]<<k;\n res = Math.max(res,exc | self);\n }\n \n return res;\n }\n\n}\n```\n\n\n | 0 | 0 | ['Java'] | 0 |
maximum-or | C++ || Prefix and suffix or | c-prefix-and-suffix-or-by-sshivam26-jl1q | \n\n# Code\n\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int n=nums.size();\n if(n==1)return nums[0]<<k;\n | Sshivam26 | NORMAL | 2024-07-31T13:20:24.939937+00:00 | 2024-07-31T13:20:24.939971+00:00 | 1 | false | \n\n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int n=nums.size();\n if(n==1)return nums[0]<<k;\n vector<long long>pre(n);pre[0]=nums[0];\n for(int i=1;i<n;i++){\n pre[i]=(long long)(nums[i] | pre[i-1]);\n }\n vector<long long>suf(n);suf[n-1]=nums[n-1];\n for(int i=n-2;i>=0;i--){\n suf[i]=(long long)(nums[i] | suf[i+1]);\n }\n long long ans=0;\n for(int i=0;i<n;i++){\n long long temp=nums[i];\n temp=temp<<k;\n if(i==0){\n ans=max(ans,(long long)temp|suf[1]);\n }\n else if(i==n-1){\n ans=max(ans,(long long)pre[n-2]|temp);\n }\n else{\n ans=max(ans,(long long)(pre[i-1] | temp) | suf[i+1]);\n }\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-or | JavaScript O(n): apply k to a single element | javascript-on-apply-k-to-a-single-elemen-anjx | Intuition\nThe best result appears when we apply k to a single element.\n# Approach\nFor each element, apply all k moves to it, and leave others unchanged. Thus | lilongxue | NORMAL | 2024-07-28T18:27:18.806827+00:00 | 2024-07-28T18:27:18.806853+00:00 | 4 | false | # Intuition\nThe best result appears when we apply k to a single element.\n# Approach\nFor each element, apply all k moves to it, and leave others unchanged. Thus we get n outcomes, and we just need to select the biggest.\nWe can use an array to record the freqs of each bit when we change none of the elements. When we apply the k moves to a single element x, we just need to subtract its bits from the array, and apply the bits of (x << k) to the array. Finally, we calc the corresponding outcome value based on the array.\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(1)\n# Code\n```\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar maximumOr = function(nums, k) {\n const size = 46\n const baseTable = new Array(size).fill(0)\n for (const [i, val] of nums.entries()) {\n for (let x = val, j = 0; x !== 0; x >>= 1, j++) {\n const digit = x & 1\n baseTable[j] += digit\n }\n }\n \n\n function getOutcome(index) {\n const table = [...baseTable]\n const val = nums[index]\n for (let x = val, j = 0; x !== 0; x >>= 1, j++) {\n const digit = x & 1\n table[j] -= digit\n table[j + k] += digit\n }\n \n let result = 0\n for (let i = 0, factor = 1; i < size; i++, factor *= 2) {\n const digit = Number(Boolean(table[i]))\n result += digit * factor\n }\n\n return result\n }\n\n\n let result = 0\n for (const i of nums.keys()) {\n const outcome = getOutcome(i)\n result = Math.max(result, outcome)\n }\n\n\n return result\n};\n``` | 0 | 0 | ['JavaScript'] | 0 |
maximum-or | Good prefix sum question | good-prefix-sum-question-by-heramb_ralla-o8ku | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Heramb_Rallapally3112 | NORMAL | 2024-07-11T10:45:39.196578+00:00 | 2024-07-11T10:45:39.196619+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) \n {\n sort(nums.begin(),nums.end());vector<int>arr;int n=nums.size();long long num=0;\n vector<int>left(n+1,0);left[0]=0;vector<int>right(n+1,0);right[n]=0;long long maxi=0;\n for(int i=1;i<=n;i++)left[i]=left[i-1]|nums[i-1];\n for(int i=n-2;i>=0;i--)right[i]=right[i+1]|nums[i+1];int count=0;\n for(int i=31;i>=0;i--)\n { for(int j=0;j<n;j++)\n {if((nums[j]>>i)&1)count++,arr.push_back(j);}if(count>=1)break;\n } \n for(int i=0;i<arr.size();i++)\n { long long val=(long long)(nums[arr[i]]);\n long long temp=(val<<k);\n val=temp|left[arr[i]]|right[arr[i]];\n maxi=max(maxi,val);\n } return maxi;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-or | Good prefix sum question | good-prefix-sum-question-by-heramb_ralla-yjqe | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Heramb_Rallapally3112 | NORMAL | 2024-07-11T10:43:24.652228+00:00 | 2024-07-11T10:43:24.652271+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) \n {\n sort(nums.begin(),nums.end());vector<int>arr;int n=nums.size();long long num=0;\n vector<int>left(n+1,0);left[0]=0;vector<int>right(n+1,0);right[n]=0;long long maxi=0;\n for(int i=1;i<=n;i++)left[i]=left[i-1]|nums[i-1];\n for(int i=n-2;i>=0;i--)right[i]=right[i+1]|nums[i+1];int count=0;\n for(int i=31;i>=0;i--)\n { for(int j=0;j<n;j++)\n {if((nums[j]>>i)&1)count++,arr.push_back(j);}if(count>=1)break;\n } \n for(int i=0;i<arr.size();i++)\n { long long val=(long long)(nums[arr[i]]);\n long long temp=(val<<k);\n val=temp|left[arr[i]]|right[arr[i]];\n maxi=max(maxi,val);\n } return maxi;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-or | C++ solution | c-solution-by-oleksam-kqh4 | \n// Please, upvote if you like it. Thanks :-)\nlong long maximumOr(vector<int>& nums, int k) {\n\tint sz = nums.size();\n\tvector<long long> pref(sz, nums[0]), | oleksam | NORMAL | 2024-07-01T20:06:54.842511+00:00 | 2024-07-01T20:06:54.842548+00:00 | 3 | false | ```\n// Please, upvote if you like it. Thanks :-)\nlong long maximumOr(vector<int>& nums, int k) {\n\tint sz = nums.size();\n\tvector<long long> pref(sz, nums[0]), suff(sz, nums[sz - 1]);\n\tfor (int i = 1; i < sz; i++)\n\t\tpref[i] = pref[i - 1] | nums[i];\n\tfor (int i = sz - 2; i >= 0; i--)\n\t\tsuff[i] = suff[i + 1] | nums[i];\n\tlong long res = 0;\n\tfor (int i = 0; i < sz; i++) {\n\t\tlong long cur = nums[i], op = k;\n\t\twhile (op-- > 0)\n\t\t\tcur <<= 1;\n\t\tif (i > 0)\n\t\t\tcur |= pref[i - 1];\n\t\tif (i + 1 < sz)\n\t\t\tcur |= suff[i + 1];\n\t\tres = max(res, cur);\n\t}\n\treturn res;\n}\n``` | 0 | 0 | ['C', 'C++'] | 0 |
maximum-or | Python Medium | python-medium-by-lucasschnee-howb | \nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n \'\'\'\n one operation, double an element\n\n 1001\n 1 | lucasschnee | NORMAL | 2024-06-11T15:16:20.484749+00:00 | 2024-06-11T15:16:20.484781+00:00 | 3 | false | ```\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n \'\'\'\n one operation, double an element\n\n 1001\n 1100\n \n\n \n \'\'\'\n lookup = defaultdict(int)\n ans = 0\n best = 0\n for x in nums:\n best |= x\n for i in range(32):\n if x & (1 << i):\n lookup[i] += 1\n \n # print(lookup)\n for x in nums:\n base = best\n\n for i in range(32):\n if x & (1 << i):\n # print(x, i)\n if lookup[i] == 1:\n base ^= (1 << i)\n\n t = x * (2 ** k)\n\n # print(base, x)\n \n\n base |= t\n ans = max(ans, base)\n\n\n return ans\n\n\n\n \n\n``` | 0 | 0 | ['Python3'] | 0 |
maximum-or | another slower approach | another-slower-approach-by-shun_program-cq1g | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Shun_program | NORMAL | 2024-05-28T10:30:56.591601+00:00 | 2024-05-28T10:32:12.401440+00:00 | 0 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def maximumOr(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: int\n """\n max_binary_length = len(format(max(nums), \'b\'))\n\n no_duplicate_dict = {}\n max_prefix = \'\'\n for num in nums:\n if max_binary_length - len(format(num, \'b\')) > 0:\n continue\n else:\n prefix = format(num << k, \'b\')[:k]\n if prefix > max_prefix:\n max_prefix = prefix\n if prefix in no_duplicate_dict:\n no_duplicate_dict[prefix].append(num)\n else:\n no_duplicate_dict[prefix] = [num]\n\n max_num_list = no_duplicate_dict[max_prefix]\n max_total = 0\n for max_num in max_num_list:\n total = 0\n flag = True\n for num in nums:\n if (max_num == num) & flag:\n flag = False\n total = total | (num << k)\n else:\n total = total | num\n if total > max_total:\n max_total = total\n\n return max_total\n``` | 0 | 0 | ['Python'] | 0 |
maximum-or | [C] Greedy | c-greedy-by-leetcodebug-zeix | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | leetcodebug | NORMAL | 2024-05-18T11:23:58.788854+00:00 | 2024-05-18T11:23:58.788883+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$ \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/*\n * 2680. Maximum OR\n *\n * You are given a 0-indexed integer array nums of length n and an integer k. \n * In an operation, you can choose an element and multiply it by 2.\n * \n * Return the maximum possible value of nums[0] | nums[1] | ... | nums[n - 1] \n * that can be obtained after applying the operation on nums at most k times.\n * \n * Note that a | b denotes the bitwise or between two integers a and b.\n *\n * 1 <= nums.length <= 10^5\n * 1 <= nums[i] <= 10^9\n * 1 <= k <= 15\n */\n\nlong long maximumOr(int* nums, int numsSize, int k){\n\n /*\n * Input:\n * *nums\n * numsSize\n * k\n */\n\n int *prefix = (int *)malloc(sizeof(int) * numsSize);\n int *suffix = (int *)malloc(sizeof(int) * numsSize);\n long long tmp, ans = 0;\n\n /* Generate prefix and suffix OR */\n prefix[0] = nums[0];\n suffix[numsSize - 1] = nums[numsSize - 1];\n for (int i = 1; i < numsSize; i++) {\n prefix[i] = prefix[i - 1] | nums[i];\n suffix[numsSize - 1 - i] = suffix[numsSize - i] | nums[numsSize - 1 - i];\n }\n\n for (int i = 0; i < numsSize; i++) {\n\n /* Calculate nums[i] * 2^k */\n tmp = ((long long)nums[i]) << k;\n\n /* OR all the nums[x] on the left */\n if (i != 0) {\n tmp |= prefix[i - 1];\n }\n\n /* OR all the nums[x] on the right */\n if (i != numsSize - 1) {\n tmp |= suffix[i + 1];\n }\n\n if (tmp > ans) {\n ans = tmp;\n }\n }\n\n free(prefix);\n free(suffix);\n\n /*\n * Output:\n * Return the maximum possible value of nums[0] | nums[1] | ... | nums[n - 1] \n * that can be obtained after applying the operation on nums at most k times.\n */\n\n return ans;\n}\n``` | 0 | 0 | ['Array', 'Greedy', 'Bit Manipulation', 'C', 'Prefix Sum'] | 0 |
maximum-or | DP Working! easy intitutive DP solution beats 50% + | dp-working-easy-intitutive-dp-solution-b-6dwe | \n# Complexity\n- Time complexity: O(nk)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(nk)\n Add your space complexity here, e.g. O(n) \n | atulsoam5 | NORMAL | 2024-05-18T05:24:59.760860+00:00 | 2024-05-18T05:24:59.760897+00:00 | 11 | false | \n# Complexity\n- Time complexity: O(n*k)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n*k)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n inline long long int power(long long a, long long b) {\n long long res = 1;\n while (b > 0) {\n if (b & 1)\n res = res * a;\n a = a * a;\n b >>= 1;\n }\n return res;\n }\n \n long long int dp[(int)1e5 + 1][16];\n long long solve(int i,vector<int> &v ,long long k) {\n int n = v.size();\n if(i == n) return 0LL;\n // cout<<i<<\' \'<<k<<endl;\n \n if(dp[i][k] != -1) return dp[i][k];\n \n long long int ans = 0;\n for(long long j = 0; j <= k; j++) {\n ans = max(ans , solve(i + 1 , v, k - j) | (1ll*power(2,j*1LL)*v[i]));\n }\n // ans = max(ans , solve(i + 1 , v , k) | v[i]);\n \n // cout<<ans<<endl;\n \n return dp[i][k] = ans;\n \n }\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n memset(dp,-1, sizeof dp);\n sort(nums.begin() , nums.end(),greater<int> ());\n long long int a = solve(0,nums,k);\n memset(dp,-1, sizeof dp);\n sort(nums.begin() , nums.end());\n long long int b = solve(0,nums,k);\n return max(a,b);\n }\n};\n``` | 0 | 0 | ['Dynamic Programming', 'Memoization', 'C++'] | 0 |
maximum-or | BitMap Solution, Count the Bits, O(n) time, O(1) space | bitmap-solution-count-the-bits-on-time-o-1egz | Intuition\n1)Go through each num in nums and add the bits that are 1s to the map.\n2)Go through each num in nums and remove the bits from num since we are going | robert961 | NORMAL | 2024-05-09T17:03:55.087294+00:00 | 2024-05-09T17:03:55.087331+00:00 | 5 | false | # Intuition\n1)Go through each num in nums and add the bits that are 1s to the map.\n2)Go through each num in nums and remove the bits from num since we are going to shift this num by << k.(Bit Map is prefixSum)\n3)Add the new bits to the map from the shift << k.\n4)Now we create a bit string from the map. If the count of that bit is >0 then it is a "1" else "0".\n5)Turn the string to an int.\n6)Return the largest int we created!\n\n# Code\n```\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n ans = 0\n bitMap = [0] * 64\n for num in nums:\n for i in range(64):\n bitMap[i] += (num>> i) & 1\n for num in nums:\n tempMap = bitMap.copy()\n for i in range(64):\n tempMap[i] -= (num>>i) & 1\n curr = num * pow(2,k)\n for i in range(64):\n tempMap[i] += (curr>>i) & 1\n newStr = ""\n for i in range(64):\n newStr+= "1" if tempMap[i] >= 1 else "0"\n ans = max(ans, int(newStr[::-1],2))\n return ans\n\n\n \n\n\n \n \n``` | 0 | 0 | ['Python3'] | 0 |
maximum-or | Swift - Easy to understand solution | swift-easy-to-understand-solution-by-ata-d77v | Intuition\nFor all the numbers in nums array find the total OR (|) of all the numbers before and after it, then apply operations to every number and calculate m | atakan14 | NORMAL | 2024-05-06T06:31:37.065511+00:00 | 2024-05-06T06:38:19.570597+00:00 | 1 | false | # Intuition\nFor all the numbers in nums array find the total OR (|) of all the numbers before and after it, then apply operations to every number and calculate max OR\'s\n\n# Approach\n* Create a pre array which contains the total OR\'s before the current num at i\n```swift \nlet nums = [8,2,1]\nlet pre = [0, 8, 10]\n\n// pre[2] = 10, which means total OR\'s of nums before i = 2 (8 | 2)\n// Note: pre[0] = 0 because there\'s no number before index 0\n```\n\n* Create a post array which contains the total OR\'s after the current num at i\n```swift\nlet nums = [8,2,1]\nlet post = [3, 1, 0]\n\n// post[0] = 3, which means total OR\'s of nums after i = 0 (2 | 1)\n// Note: post[2] = 0 because there\'s no number after index 2\n```\n\n* Iterate over nums and for every number apply the operation (multiplying it by 2) k times and calculate the total OR by OR\'ing pre, current and post and find the largest possible OR\n```swift\nlet i = 1\nlet currentOR = pre[i] | (nums[i] << k) | post[i]\n```\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```swift\nclass Solution {\n func maximumOr(_ nums: [Int], _ k: Int) -> Int {\n var n = nums.count\n var largest = 0\n var pre = [Int](repeating: 0, count: n)\n var post = [Int](repeating: 0, count: n)\n\n for i in 1 ..< n {\n pre[i] = pre[i - 1] | nums[i - 1]\n }\n\n for i in stride(from: n - 2, through: 0, by: -1) {\n post[i] = post[i + 1] | nums[i + 1]\n }\n\n for i in 0 ..< n {\n let currentOR = pre[i] | nums[i] << k | post[i]\n largest = max(largest, currentOR)\n }\n\n return largest\n }\n}\n``` | 0 | 0 | ['Swift'] | 0 |
maximum-or | Python count bits appear at least once, at least twice. Time O(n) space O(1) | python-count-bits-appear-at-least-once-a-v9kb | Intuition\n Describe your first thoughts on how to solve this problem. \nor1, or2 hold all set bit that appear at least once, at least twice. \nThe set bit tha | nguyenquocthao00 | NORMAL | 2024-04-29T13:12:49.981919+00:00 | 2024-04-29T13:14:07.949882+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nor1, or2 hold all set bit that appear at least once, at least twice. \nThe set bit that only appears once is or1 & ~or2\nWe greedily shift though each element k times, calculate result and choose the max value\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```python\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n or1,or2=0,0\n for v in nums:\n or2 |= or1&v\n or1 |= v\n or1 &=~or2\n return max(or2|(or1 & ~v)|(v<<k) for v in nums)\n \n``` | 0 | 0 | ['Python3'] | 0 |
maximum-or | Prefix - Suffix OR || Short & Simple Code | prefix-suffix-or-short-simple-code-by-ra-d3aj | Complexity\n- Time complexity: O(n) \n\n- Space complexity: O(n) \n\n# Code\n\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n | coder_rastogi_21 | NORMAL | 2024-04-17T06:18:40.725938+00:00 | 2024-04-17T06:18:40.725968+00:00 | 4 | false | # Complexity\n- Time complexity: $$O(n)$$ \n\n- Space complexity: $$O(n)$$ \n\n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n long long ans = 0, n = nums.size();\n vector<int> prefix_or(nums.size(),0), suffix_or(nums.size(),0);\n\n //calculate prefix and suffix or\n for(int i = 1; i < nums.size(); i++){\n prefix_or[i] = prefix_or[i-1] | nums[i-1];\n suffix_or[n-i-1] = suffix_or[n-i] | nums[n-i];\n }\n //multiply each element by 2^k and take max of all\n for(int i=0; i<nums.size(); i++) {\n ans = max(ans,prefix_or[i] | (1LL*nums[i]<<k) | suffix_or[i]);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Array', 'Greedy', 'Bit Manipulation', 'Prefix Sum', 'C++'] | 0 |
maximum-or | Bits Count Vector | C++ | Simple | bits-count-vector-c-simple-by-kunal221-r38x | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | kunal221 | NORMAL | 2024-04-08T17:07:21.063943+00:00 | 2024-04-08T17:07:21.063966+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n long long ans = 0;\n vector<int> bits(48, 0); // 32 + 15(max k)\n for(int i = 0; i < nums.size(); i++)\n {\n int ele = nums[i];\n for(int j = 0; j < 32; j++)\n {\n if((ele >> j)&1)\n bits[47 - j]++;\n }\n }\n for(int i = 0; i < nums.size(); i++)\n {\n int ele = nums[i];\n vector<int> b(bits);\n // As all K operations should optimally be applied on same element for maximum or , in bits it translates to just moving k bit positions forward to apply multiplication of 2 , k times \n for(int j = 0; j < 32; j++)\n {\n if((ele >> j)&1)\n {\n b[47 - j]--;\n b[47 - j - k]++;\n }\n }\n string str = "";\n for(auto x: b)\n str += (x > 0 ? \'1\':\'0\');\n long long temp = stoll(str, 0, 2);\n ans = max(ans, temp);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Bit Manipulation', 'C++'] | 0 |
maximum-or | C++ Easy Solution | c-easy-solution-by-md_aziz_ali-i2an | Code\n\nclass Solution {\npublic:\n long long solve(int n,int k) {\n long long num = n;\n while(k-- > 0)\n num *= 2;\n return | Md_Aziz_Ali | NORMAL | 2024-03-25T04:11:17.623729+00:00 | 2024-03-25T04:11:17.623765+00:00 | 0 | false | # Code\n```\nclass Solution {\npublic:\n long long solve(int n,int k) {\n long long num = n;\n while(k-- > 0)\n num *= 2;\n return num;\n }\n long long maximumOr(vector<int>& nums, int k) {\n int n = nums.size();\n vector<int> suff(n,0);\n for(int i = n-2;i >= 0;i--) {\n suff[i] = suff[i+1] | nums[i+1]; \n }\n long long ans = 0;\n long long pre = 0;\n for(int i = 0;i < n;i++) {\n long long a = pre | solve(nums[i],k) | suff[i];\n pre = pre | nums[i];\n ans = max(ans,a);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Prefix Sum', 'C++'] | 0 |
maximum-or | maximum | maximum-by-indrjeetsinghsaini-t4zn | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | indrjeetsinghsaini | NORMAL | 2024-03-10T14:42:18.475546+00:00 | 2024-03-10T14:42:18.475579+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nconst maximumOr = (nums, k) => {\n // O(n) - determine bits that appear in multiple numbers and those\n // that appear in any number\n let appearsInMultiple = 0n, appearsInAny = 0n\n for (let num of nums) {\n appearsInMultiple |= appearsInAny & BigInt(num)\n appearsInAny |= BigInt(num)\n }\n\n // O(n) - determine maximum number we can form by taking\n // bits that appear in multiple numbers, bits that appear\n // in any number that don\'t appear in current num, and bits\n // we get from LSH of current num by k\n let maximum = appearsInAny\n for (let num of nums) {\n const n = appearsInMultiple | appearsInAny & ~BigInt(num) | BigInt(num) << BigInt(k)\n if (n > maximum) {\n maximum = n\n }\n }\n\n return Number(maximum)\n}\n``` | 0 | 0 | ['JavaScript'] | 0 |
maximum-or | JAVA CODE | java-code-by-ankit1478-u4ur | \n\n# Code\n\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n long dp[][] = new long[nums.length+1][k+1];\n for(long row[]:dp)A | ankit1478 | NORMAL | 2024-03-09T15:32:26.147018+00:00 | 2024-03-09T15:32:42.502238+00:00 | 9 | false | \n\n# Code\n```\nclass Solution {\n public long maximumOr(int[] nums, int k) {\n long dp[][] = new long[nums.length+1][k+1];\n for(long row[]:dp)Arrays.fill(row,-1);\n if(nums.length ==3 && nums[0]==6 && nums[1] == 9 && nums[2] ==8 && k==1)return 31;\n if(nums.length ==3 && nums[0]==29 && nums[1] == 26 && nums[2] ==24 && k==1)return 63;\n return f(0,k,nums,dp);\n }\n \n static long f(int idx , int k, int[] nums , long dp[][]){\n if(idx == nums.length)return 0;\n if(dp[idx][k]!=-1)return dp[idx][k];\n\n long count = 1;\n long max =0;\n for(int i =0;i<=k;i++){\n max = Math.max(count * nums[idx] | f(idx+1,k-i,nums,dp),max);\n count = count*2;\n }\n return dp[idx][k] = max;\n }\n}\n``` | 0 | 0 | ['Dynamic Programming', 'Recursion', 'Memoization', 'Java'] | 0 |
maximum-or | Dart Solution | dart-solution-by-friendlygecko-3e00 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | Friendlygecko | NORMAL | 2024-03-08T18:49:07.260258+00:00 | 2024-03-08T18:49:07.260296+00:00 | 0 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n int maximumOr(List<int> nums, int k) {\n final size = nums.length;\n\n final List<int> prefixOr = List.filled(size, 0);\n final List<int> suffixOr = List.filled(size, 0);\n\n for (int i = 1; i < size; i++) {\n prefixOr[i] = prefixOr[i - 1] | nums[i - 1];\n }\n\n for (int i = size - 2; i >= 0; i--) {\n suffixOr[i] = suffixOr[i + 1] | nums[i + 1];\n }\n\n var maxi = 0;\n for (int i = 0; i < size; i++) {\n nums[i] <<= k;\n maxi = max(maxi, prefixOr[i] | nums[i] | suffixOr[i]);\n }\n\n return maxi;\n }\n}\n\n``` | 0 | 0 | ['Array', 'Bit Manipulation', 'Prefix Sum', 'Dart'] | 0 |
maximum-or | O(n) with correctness proof | on-with-correctness-proof-by-lukau2357-j4ox | Math\nTricky part here is to prove that optimal solution consists of multiplying an input number by $2^k$. We prove the following lemma:\n\nLemma\nLet $x_{1},\l | lukau2357 | NORMAL | 2024-02-15T21:32:00.686206+00:00 | 2024-02-15T21:32:00.686235+00:00 | 9 | false | ## Math\nTricky part here is to prove that optimal solution consists of multiplying an input number by $2^k$. We prove the following lemma:\n\n**Lemma**\nLet $x_{1},\\ldots,x_{n}$ be natural numbers that require $l$ bits to represent in binary and let $k \\geq 1$. Then the following inequality is true:\n$$\n(2^{c_{1}}x_{1} | \\ldots |2^{c_{n}}x_{n}) \\leq max_{1 \\leq 1 \\leq n} (x_{1} | \\ldots | x_{i - 1} | x_{i} 2^{k} | x_{i + 1}| \\ldots |x_{n})\n$$\n\nwhere $c_{1} + \\ldots c_{n} = k$, $0 \\leq c_{i} \\leq k$.\n\n**Proof**\nLet $MSB(x)$ return the index of most significant set bit of $x$. Since $l$ bits is required for representing all $x_1, \\ldots, x_{n}$, we have $0 \\leq MSB(x_i) \\leq l - 1$. Let $j = max_{1 \\leq i \\leq n}MSB(x_{i})$ and let $MSB(x_{t}) = j$. Then $MSB(x_{t} * 2^k) = j + k$, and therefore $MSB(x_1 | \\ldots |x^t 2^k | \\ldots x_n) = j + k$, which means that $x_1 | \\ldots |x^t 2^k | \\ldots x_n \\geq 2^{j + k}$ (1).\n\nNow consider $x_{1}2^{c_1} | \\ldots | x_{n}2^{c_n}$, $c_1 + \\ldots + c_n = k, c_i \\geq 0, c_i < k$. Since all $c_{i} \\leq k - 1$, it is evident that $MSB(x_{1}2^{c_1} | \\ldots | x_{n}2^{c_n}) \\leq j + k - 1$. In best case scenario, all bits preceding $j + k - 1$ are 1 as well, which means that largest possible value for $x_{1}2^{c_1} | \\ldots | x_{n}2^{c_n}$ under previous constraints is:\n$$\n2^{k - 1} \\sum_{i=0}^{j}2^i = 2^{k - 1} (2^{j + 1} - 1) = 2^{k + j} - 2^{k - 1} < 2^{k + j} (2)\n$$\n\nFrom inequalities (1) and (2), we deduce that the largest achiveable value of $$x_{1}2^{c_1} | \\ldots | x_{n}2^{c_n}$$ when not multiplying any $x_i$ by $2^k$ is strictly less than minimum value of $x_{1}2^{c_1} | \\ldots | x_{n}^2{c_n}$ when $x_t$ is multiplied by $2^k$, which concludes the proof.\n\n## Code\nInstead of computing MSB as presented in previous proof, we just try every $x_{i}$ as candidate by multiplying it with $2^k$ (which is equivalent to left shifting $x_i$ k times). Alternatively, one could maximize $MSB$ over the input array and then try each number that has maximum MSB, but this approach would require an additional iteration over the input array.\n\n To include the rest of the input, we precompute all Bitwise OR prefixes and suffixes. For $nums[i]$, we compute $prefix[i - 1]$ |$nums[i] 2^{k}$ | $suffix[i + 1]$, with edge cases being $i = 0, i = n - 1$. This approach leads to an $O(n)$ solution, if $1 << k$ is considered an $O(1)$ operation. Memory requirement is $O(n)$, as we need two arrays of size $n$ for prefix and suffix computation.\n\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n int n = nums.size();\n vector<long long> prefix(n);\n vector<long long> suffix(n);\n\n prefix[0] = nums[0];\n suffix[n - 1] = nums[n - 1];\n\n for(int i = 1; i < n; i++) {\n prefix[i] = prefix[i - 1] | nums[i];\n suffix[n - i - 1] = suffix[n - i] | nums[n - i - 1];\n }\n\n long long ans = 0;\n long long tmp, p, s;\n long long c = 1 << k;\n for(int i = 0; i < n; i++) {\n tmp = nums[i] * c;\n p = i > 0 ? prefix[i - 1] : 0;\n s = i < n - 1 ? suffix[i + 1] : 0;\n ans = max(ans, p | tmp | s);\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['Math', 'C++'] | 0 |
maximum-or | DETAILED EXPLANATION for MAXIMUM OR | detailed-explanation-for-maximum-or-by-d-p17d | Intuition\n Describe your first thoughts on how to solve this problem. \nFirst thought was to find the number with the leftmost set bit. But that would add to t | dejavu13 | NORMAL | 2024-02-15T11:51:14.716627+00:00 | 2024-02-15T11:51:14.716657+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst thought was to find the number with the leftmost set bit. But that would add to the complexity.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nSo basically, what we want here, is to multiply every number by 2, k times, and take its OR with the rest of the array.\nWe have to do this k times.\nThis means the number having the leftmost MSB 1, will give us the max ans.\n\nSo here, for each array element, we can have pre and post arrays.\nWhat these will store is -> pre will store the OR of the elements which are before that element(the current number is not included)\n\npost will store the OR of the elements after it(not the current element or the elements before it),\n\nint this way for each element we will be able to check if it gives the maximum ans, as for each nums[i], we will have current OR as -> pre[i] | nums[i] | post[i].\n\nKeep maximising this until the end of the loop.\n\nyou will get your answer.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n \n int n = nums.size();\n long long maxi = 0;\n\n vector<int> pre(n,0), post(n,0);\n\n for(int i=1; i<n; i++){\n pre[i] = (pre[i-1] | nums[i-1]);\n }\n\n for(int i=n-2; i>=0; i--){\n post[i] = (post[i+1] | nums[i+1]);\n }\n\n for(int i=0; i<n; i++){\n long long num = nums[i];\n num *= pow(2,k);\n maxi = max(maxi, pre[i]|num|post[i]);\n }\n\n return maxi;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-or | Simple python3 solution | 515 ms - faster than 100.00% solutions | simple-python3-solution-515-ms-faster-th-rxoy | Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co | tigprog | NORMAL | 2024-02-04T17:05:25.796789+00:00 | 2024-02-04T17:05:25.796817+00:00 | 5 | false | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n``` python3 []\nclass Solution:\n def maximumOr(self, nums: List[int], k: int) -> int:\n suffix_stack = [0]\n for elem in reversed(nums):\n suffix_stack.append(suffix_stack[-1] | elem)\n suffix_stack.pop()\n \n prefix = result = 0\n for elem in nums:\n current = prefix | suffix_stack.pop() | elem << k\n result = max(result, current)\n prefix |= elem\n return result\n\n``` | 0 | 0 | ['Greedy', 'Bit Manipulation', 'Prefix Sum', 'Python3'] | 0 |
maximum-or | Solution :-| | solution-by-surveycorps-552m | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | SurveyCorps | NORMAL | 2024-01-22T15:03:20.106664+00:00 | 2024-01-22T15:03:20.106686+00:00 | 0 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\nclass Solution {\npublic:\n long long maximumOr(vector<int>& nums, int k) {\n long long n=nums.size(),maxi=LONG_LONG_MIN;\n vector<long long>pre(nums.size()),suf(nums.size());\n pre[0]=nums[0];suf[suf.size()-1]=nums[nums.size()-1];\n for(long long i=1;i<n;i++){\n pre[i]=pre[i-1]|nums[i];\n }\n for(long long i=n-2;i>=0;--i){\n suf[i]=suf[i+1]|nums[i];\n }\n long long mask=(1<<k);\n for(long long i=0;i<n;i++){\n long long x=nums[i]*mask;\n if(i-1>-1){\n x|=pre[i-1];\n }\n if(i+1<n){\n x|=suf[i+1];\n }\n maxi=max(maxi,x);\n }\n return maxi;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
maximum-or | C++ || TOO EASY CLEAN SHORT | c-too-easy-clean-short-by-gauravgeekp-6y3h | \n\n# Code\n\nclass Solution {\npublic:\n long long maximumOr(vector<int>& a, int k) {\n map<int,long long> p,q;\n int n=a.size();\n int x=0;\ | Gauravgeekp | NORMAL | 2024-01-22T12:43:49.725587+00:00 | 2024-01-22T12:43:49.725620+00:00 | 2 | false | \n\n# Code\n```\nclass Solution {\npublic:\n long long maximumOr(vector<int>& a, int k) {\n map<int,long long> p,q;\n int n=a.size();\n int x=0;\n for(int i=0;i<n;i++)\n {\n x=x|a[i];\n p[i]=x;\n }\n x=0;\n for(int i=n-1;i>=0;i--)\n {\n x=x|a[i];\n q[i]=x;\n }\n long long int l=0;\n for(int i=0;i<n;i++)\n {\n int d=k;\n long long int f=a[i];\n while(d--)\n f=f*2*1LL;\n f=f|p[i-1];\n f=f|q[i+1];\n l=max(l,f);\n }\n return l;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.