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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
maximum-xor-after-operations | ✅ One Line Solution | one-line-solution-by-mikposp-wpwr | Time complexity: O(n). Space complexity: O(1). | MikPosp | NORMAL | 2024-11-20T13:56:15.393868+00:00 | 2025-04-06T09:27:38.968992+00:00 | 40 | false | Time complexity: $$O(n)$$. Space complexity: $$O(1)$$.
```python3
class Solution:
def maximumXOR(self, a: List[int]) -> int:
return reduce(or_,a)
``` | 2 | 0 | ['Array', 'Bit Manipulation', 'Python', 'Python3'] | 0 |
maximum-xor-after-operations | Simple bit manipulation solution with explanation | simple-bit-manipulation-solution-with-ex-nn7n | Intuition\n Describe your first thoughts on how to solve this problem. \n- You may see that AND operator will always reduce number of bits. Therefore nums[i] AN | trieutrng | NORMAL | 2024-10-09T07:44:05.472732+00:00 | 2024-10-09T07:52:31.552949+00:00 | 59 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- You may see that AND operator will always reduce number of bits. Therefore nums[i] AND (nums[i] XOR x) will be used to turn off bits\n- When we XOR all numbers of an array $$[a1, a2, a3, ...]$$, all the bits whose occurences is even number will be turned off. Keep turned on for odd.\n- Therefore, to form a maximum number, all we need to do is simply keep as many turned on bits as possible\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Use OR operator to construct a maximal number (because OR will keep the bit no matter its occurences is even or odd)\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```python3 []\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n ans = 0\n for num in nums:\n ans |= num\n return ans\n``` | 2 | 0 | ['Math', 'Bit Manipulation', 'Python3'] | 0 |
maximum-xor-after-operations | [Python] OR all elements | python-or-all-elements-by-pbelskiy-4n7k | python\n"""\nFirst of all it\'s easy taks, if we look create table of binary \nrepresentation of nums, it will be clear that anser is OR sum.\n\nFor example [1, | pbelskiy | NORMAL | 2023-09-25T15:49:43.143417+00:00 | 2023-09-25T15:49:43.143465+00:00 | 143 | false | ```python\n"""\nFirst of all it\'s easy taks, if we look create table of binary \nrepresentation of nums, it will be clear that anser is OR sum.\n\nFor example [1,2,3,9,2]\n\n1 - 0001\n2 - 0010\n3 - 0011\n9 - 1001\n2 - 0010\n\nUsing `nums[i] AND (nums[i] XOR x)` we actually can zero any i th bit.\n\nSo it\'s clear that if i th bit is 0 everywhere, we cannot convert it\nto 1, if any i th bit is 1 anywhere, we can conver rest of it to zero.\n\nSo our result will be sum of OR.\n\nTC: O(N)\nSC: O(1)\n"""\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n r = 0\n for n in nums:\n r |= n\n return r\n``` | 2 | 0 | ['Python'] | 0 |
maximum-xor-after-operations | Maximum XOR After Operations Solution in C++ | maximum-xor-after-operations-solution-in-ech8 | 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 | The_Kunal_Singh | NORMAL | 2023-04-22T06:46:32.575709+00:00 | 2023-04-27T16:28:27.695775+00:00 | 336 | 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)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans=0;\n for(auto it:nums)\n {\n ans |= it;\n }\n return ans;\n }\n};\n```\n\n | 2 | 0 | ['C++'] | 0 |
maximum-xor-after-operations | Python One Line (Detailed Explanation) | python-one-line-detailed-explanation-by-4e5rl | Intuition\n Describe your first thoughts on how to solve this problem. \nThis problem relies on a few key observations made in sequence, which lend themselves t | likey_00 | NORMAL | 2023-03-25T04:17:50.509652+00:00 | 2023-03-25T04:17:50.509700+00:00 | 418 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem relies on a few key observations made in sequence, which lend themselves to a very elegant solution.\n\nObservation 1: Since x is arbitrary, we can make (nums[i] XOR x) anything we like. For a given target number T = (nums[i] XOR x), we can construct x bit by bit. If the jth bit of T is 1, then the jth bit of x differs from the jth bit of nums[i]. If the jth bit of T is 0, then the jth bit of x is the same as the jth bit of nums[i].\n\nObservation 2: We can set nums[i] to anything using the bits ALREADY in nums[i]. We want to set nums[i] equal to nums[i] AND (nums[i] XOR x). We already know T = (nums[i] XOR x) is arbitrary. We can turn off any bits in nums[i] by making those bits in T zero, but we cannot produce any new bits, since they must be ANDed by zeros in nums[i].\n\nObservation 3: We can obtain any bit present in any of the nums[i] in our final XOR. All we need to do is leave one instance of each bit present in some nums[i], and turn off all other copies of that bit. Then when we XOR all of that bit together, we\'ll get 1 XOR 0 XOR 0... which is just 1. Note we can\'t produce any bit outside of the nums[i] since XORing zeros can only produce zero. \n\nObservation 4: Taking all the bits present in nums boils down to taking the bitwise OR of all the numbers. This operation will turn on a bit if at least one of the nums[i] has this bit set to 1.\n\n# Implementation\n<!-- Describe your approach to solving the problem. -->\nWe can write a simple for loop that maintains a solution variable starting at zero, and ORs every nums[i] with it. This will work, but we can express the same idea a little cleaner with functools.reduce()\n\nReduce takes in a function which maps 2 values down to 1 value, and applies it to our list. It will reduce the first 2 list values into 1 value, then reduce that and the next list value to 1 value, continuing to absorb the whole list. \n\nOur reducing funtion is simply the bitwise OR, as we want to OR the first 2 elements, then OR that with the next element, then OR that with the next element, and so on. \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:\n def maximumXOR(self, nums: List[int]) -> int:\n return reduce(lambda x, y: x | y, nums)\n``` | 2 | 0 | ['Python3'] | 0 |
maximum-xor-after-operations | [Java] %100 O(n) | java-100-on-by-zeldox-letz | \n# Approach\n Describe your approach to solving the problem. \nXOR means check all the bits and make or operations so if we apply this for all the array member | zeldox | NORMAL | 2023-01-10T10:58:52.284427+00:00 | 2023-01-10T10:58:52.284470+00:00 | 1,206 | false | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nXOR means check all the bits and make or operations so if we apply this for all the array member we can reach the maximum value\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(1)$$ \n# Code\n```\nclass Solution {\n public int maximumXOR(int[] nums) {\n int res = 0;\n for (int a: nums)\n res |= a;\n return res;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
maximum-xor-after-operations | Bitmanipulation | bitmanipulation-by-mani_himanshu-2k5d | Intuition\n Describe your first thoughts on how to solve this problem. \n Bit Manipulation.\n Here we have A & (A ^ B), now if A = 9 (ie 1 0 0 1), now A & | Mani_Himanshu | NORMAL | 2022-12-31T17:13:36.822891+00:00 | 2022-12-31T17:14:46.515454+00:00 | 477 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n Bit Manipulation.\n Here we have A & (A ^ B), now if A = 9 (ie 1 0 0 1), now A & (A ^ B) can not be more than 9, because we are anding A ^ B with A, so here we know that iff the bit is 1 it can be 0, but we can not make 0 to 1.\n therefore we need to just bitwise OR each number (it there is 1 at that bit in any number than we can get that 1 in ans, however iff there is 0 at that bit in all numbers than it will be 0).\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n So just bitwise OR all the numbers. \n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# Code\n```\nclass Solution {\n public int maximumXOR(int[] nums) {\n int ans=0;\n for(int num: nums) ans |= num;\n return ans;\n }\n}\n``` | 2 | 0 | ['Java'] | 1 |
maximum-xor-after-operations | C++ || Well-commented || Brute force approach || Bitmasks || Clean solution | c-well-commented-brute-force-approach-bi-6jsc | \n/* Intution -> \n If we write the binary representation of the nums, we can observe that \n if we manage to find atleast one setbit at that position ac | jainshreyansh163 | NORMAL | 2022-10-31T11:33:48.600355+00:00 | 2022-10-31T11:33:48.600398+00:00 | 68 | false | ```\n/* Intution -> \n If we write the binary representation of the nums, we can observe that \n if we manage to find atleast one setbit at that position across nums, \n\tthen we can simply take its contribution bcoz on changing a number \n\tby the given AND operation, we won\'t end up with a setbit.\n\t( 0&0=1 1&1=1 0&1=1 1&0=1).\n\t\n\tSummary -> \n\tSo, at a particular position, if you find a setbit, just take its contribution\n*/\nint maximumXOR(vector<int>& nums) {\n // Border case -> [0] (as log function won\'t work for it) \n int n = nums.size();\n if(n==1) return nums[0];\n\t\t\n // Taking out the max. bits to which we need to check\n int x = *max_element(nums.begin(),nums.end());\n int bits = log(x)/log(2) + 1;\n int j = 0, ans = 0;\n \n while(bits--) {\n int c = 0;\n for(auto i:nums) {\n\t\t\t//If that particular bit is found to be set, then take its contribution\n if(i&(1<<j)) {\n c = 1; \n ans += (pow(2,j));\n break;\n }\n }\n j++;\n }\n \n return ans;\n }\n``` | 2 | 0 | ['C', 'Bitmask'] | 0 |
maximum-xor-after-operations | ✅Two Approaches || Easy, Short & Best Code in C++✅✅ | two-approaches-easy-short-best-code-in-c-tpuo | Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(1)\n\n# Code\nPlease Upvote if u liked my Solution\uD83D\uDE42\n\n1st Approach:-\n\nclass Solution | aDish_21 | NORMAL | 2022-10-22T09:46:53.427755+00:00 | 2022-10-22T09:57:39.072858+00:00 | 588 | false | # Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(1)\n\n# Code\n**Please Upvote if u liked my Solution**\uD83D\uDE42\n\n***1st Approach:-***\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int xoR=0;\n for(auto it:nums)\n xoR |= it;\n return xoR;\n }\n};\n```\n***2nd Approach:-***\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int size=nums.size(),xoR=0;\n for(auto it:nums)\n xoR^=it;\n for(int i=0;i<32;i++){\n if((xoR & 1<<i))\n continue;\n for(int j=0;j<size;j++){\n if((nums[j] & 1<<i)){\n xoR^=1<<i;\n break;\n }\n }\n }\n return xoR;\n }\n};\n```\n | 2 | 0 | ['Array', 'Math', 'Bit Manipulation', 'C++'] | 1 |
maximum-xor-after-operations | 70% BEATS || EASY || SIMPLE || C++ || TIME O(1) || SPACE O(1) | 70-beats-easy-simple-c-time-o1-space-o1-xscl9 | \nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n vector<int> v(32,0);\n int j = 0;\n for(auto &i: nums){\n | abhay_12345 | NORMAL | 2022-09-08T07:50:20.988564+00:00 | 2022-09-08T07:50:20.988611+00:00 | 339 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n vector<int> v(32,0);\n int j = 0;\n for(auto &i: nums){\n j = 0;\n while(i){\n v[j] += i&1;\n i = i >> 1;\n j++;\n }\n }\n int ans = 0;\n for(j = 0; j < 32; j++){\n if(v[j]) ans += (1<<j);\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['Bit Manipulation', 'C', 'C++'] | 0 |
maximum-xor-after-operations | 2 Solutions | OR and Bit Shifting | Python | 2-solutions-or-and-bit-shifting-python-b-ho2l | Intuition\nWe have to use AND (&) after some XOR (^) operation.\n\nApplying & will not be able to toggle bits set to 0 into 1.\n\nApplying XOR ^ we are able to | nadaralp | NORMAL | 2022-06-26T16:08:45.455334+00:00 | 2022-06-26T16:08:45.455383+00:00 | 126 | false | # Intuition\nWe have to use AND (&) after some XOR (^) operation.\n\nApplying `&` will not be able to toggle bits set to 0 into 1.\n\nApplying XOR `^` we are able to flip the bits.\n\nThe idea is to flip all the bits we can to 1, by doing this we will be able to maximize the result. \n\nFor example if we are able to flip all the bits to 1\n1111 ^ 0000 => 1111.\n\n\n# First solution\nApply cumulative `OR (|)` to turn all the possible bits on.\n\n```\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n res = 0\n for v in nums: res |= v\n return res\n```\n\n# Second solution\nSave an array that represents the bits.\n\nIterate over nums and put bits[i] to 1 if it is active in current num.\n\nDo this for all numbers, and then return the number that is represented by the bits.\n\n```\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n\t\t# 32 bit integer\n bits = [0] * 32\n \n # Try to maximize all bits to 1\n for n in nums:\n for i in range(31, -1, -1):\n bits[i] = max(bits[i], n>>i&1)\n \n res = 0\n for i, v in enumerate(bits):\n # Accumulate result by shifting left to retrieve the open bit value\n res += v<<i\n \n return res\n``` | 2 | 0 | ['Python'] | 0 |
maximum-xor-after-operations | C++ O(32*n) code with Detailed Explanation | c-o32n-code-with-detailed-explanation-by-bwi4 | Observe that a&(a^x) = (a&a)^(a&x) = a^(a&x)\nObserve that (a&x) will be set only on those bits which is already 1.\nie. if a has a binary representation of \n\ | akshatanand186 | NORMAL | 2022-06-26T09:43:17.998179+00:00 | 2022-06-26T09:43:17.998207+00:00 | 48 | false | Observe that **a&(a^x) = (a&a)^(a&x) = a^(a&x)**\nObserve that **(a&x)** will be set only on those bits which is already 1.\nie. if a has a binary representation of \n\na = 100011\nthen a&x can be 100001, 100010, 100011, 000011, 000010, 000001, 000000.\n\nNow the XOR of this A&X will make those bits off which is present in (a&x), \nthus we can set X accordingly and set any bit of A as off.\n\nNow for maximum XOR of array, we need to look bitwise at each position and check if there is atleast one number which has this bit on, if yes, then we can make this bit on in the answer(by switching off all bits in rest of array at this position) else we can\'t.\n\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int n = nums.size();\n int num = 0;\n for(int i=0;i<32;i++){\n for(int j=0;j<n;j++){\n int x = (nums[j]>>i);\n if(x%2) {num += (1<<i); break;}\n }\n }\n return num;\n }\n};\n``` | 2 | 0 | [] | 0 |
maximum-xor-after-operations | Java || simple || explanation O(31 * N) | java-simple-explanation-o31-n-by-lagahua-tbty | if we consider ith bit of numbers then we can notice that \n if the number of set bits are odd then XOR of that position will be 1.\n if the number of set bits | lagaHuaHuBro | NORMAL | 2022-06-25T19:06:15.899306+00:00 | 2022-06-25T19:10:24.713707+00:00 | 36 | false | if we consider ```ith``` bit of numbers then we can notice that \n* if the number of set bits are odd then ```XOR``` of that position will be ```1```.\n* if the number of set bits are even then ```XOR``` of that position will be ```0```.\n\nwe know that taking ```and``` of a number with any other number can never increase the given number.\ni.e. ```result``` of ```x & y``` will always be ```<= x``` no matter what the value of ```y``` is.\n\n* if we want to maximize our ```result``` then we want to have maximum number of set bits possible in our answer.\n* now, if the number of set bits at a position is ```odd``` which is what we want then we set the corresponding bit to ```1``` in the answer.\n* if the corresponding number of set bits is ```even``` then we want to flip one bit of any number to make the count of set bits ```odd``` at that position.\n\n```\nclass Solution {\n public int maximumXOR(int[] nums) {\n\t int answer = 0;\n for (int i = 0; i < 31; i++) {\n int bits = 0;\n int mask = (1 << i);\n for (int n : nums) {\n if ((mask & n) > 0) {\n bits++;\n }\n }\n if (bits > 0) {\n\t\t\t // we could flip any ith bit in any nuber and make the xor 1\n\t\t\t\t// but we can not set an odd bit \n answer |= (1 << i);\n }\n }\n return answer;\n }\n} | 2 | 0 | [] | 0 |
maximum-xor-after-operations | C++ || Clean and concise solution || O(n) time O(1) space | c-clean-and-concise-solution-on-time-o1-38zzv | \nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n long long k=0;\n int ans=0;\n for(int i=0;i<32;i++)\n {\n | ashay028 | NORMAL | 2022-06-25T17:12:48.222166+00:00 | 2022-06-25T17:13:24.114835+00:00 | 78 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n long long k=0;\n int ans=0;\n for(int i=0;i<32;i++)\n {\n k= (1<<i);\n for(auto &it : nums)\n {\n if(it&k)\n {\n ans+=(1<<i);\n break;\n }\n }\n }\n return ans;\n }\n};\n``` | 2 | 0 | [] | 0 |
maximum-xor-after-operations | Python | O(n) Explanation for people struggling with Bitwise. | python-on-explanation-for-people-struggl-yiwf | Things to notice\n\nAND Operator\n\nBasically i AND j is used to find the bits set in both i and j.\nFor example.\n\nBitwise AND of 1001010, 1001100 is\n1001010 | surajajaydwivedi | NORMAL | 2022-06-25T17:12:46.331031+00:00 | 2022-06-25T18:03:14.773340+00:00 | 78 | false | **Things to notice**\n\n**AND Operator**\n\nBasically *i AND j* is used to find the bits set in both *i* and *j*.\nFor example.\n\nBitwise AND of 1001010, 1001100 is\n1001010\n1001100\n*=*\n1001000\n\nSo we can realise that \n* no new bit can be set by the AND operator.\n* AND of any number with 0 is 0.\n* To unset ith bit of a number, use AND operator of number with all bits set except ith.\n\n**XOR operator**\n*i XOR j* sets the uncommon bits between *i* and *j*, while unsetting the common ones.\nFor example.\n\nBitwise XOR of 1001010, 1001100 is\n1001010\n1001100\n*=*\n0110111\n\nSo we can realise that\n* We can realistically create any number with XOR operator of *i* and j, if we specifically pick j.\n* Explanation of above point, to create 7 *(1001)* from 3 *(11)*, we can XOR it with 10 *(1010)*.\n* XOR of any number with itself, is 0.\n\n**Intuition**\n\nIf we look at `nums[i] AND (nums[i] XOR x)` and combine it with points mentioned above.\n* If we can select any non-negative integer x. `(nums[i] XOR x)` basically can become any number we want.\n* We will denote this new number as **y**.\n* `nums[i] AND y` can never exceed minimum(nums[i],y), and no new bit can be set which aren\'t already set in nums[i].\n* So no matter what operations we perform. If kth bit is unset in all nums[i] in nums, it can never be set.\n* To find maximum XOR, it will be best to keep kth bit set only in odd amount of numbers, as even numbers will unset the kth bit.\n* We can perform specific operations, such that kth bit is set in at most 1 nums[i], for all k, after all the operations.\n* Maximum answer will only be the one with most bits set.\n\n**Solution**\n\nWe need to find all the k, for which the kth bit is set in any of the numbers. We can then assume that these bits are set in only at most 1 nums[i] each, at the end of all operations. We do not necesarrily need to find the exact nums at the end as we learnt above that it is possible to unset any bit in any nums[i] due to `nums[i] AND (nums[i] XOR x)`.\n\nAs maximum integer is 10^8. There are 27 bits at most.\n\nIterate over each nums[i], and check if kth bit is set for k in range(1,27).\nKeep another array to maintain if kth bit is set in at least 1 of nums[i] or not.\n\nThe final answer will simply be to convert the new formed array into int.\n\nExample.\n\nnums = [3,2,4,6]\n3 = 0011\n2 = 0010\n4 = 0100\n6 = 0110\n\nsetbits = [1110] (leftmost bit means 1st bit and so on.)\nSo final answer = 1x1 + 2x1 + 4x1 + 8x0. = 7.\nOne possible nums array (after operations) for the same can be [1,0,0,6]\n1 = 3 & ( 3 ^ 2 )\n0 = 2 & ( 2 ^ 2 )\n0 = 4 & ( 4 ^ 4 )\n6 = 6 & ( 6 ^ 1 )\n\nNow XOR of 1^0^0^6 = 7.\n\nMy python accepted code.\n\n```\ndef maximumXOR(self, nums: List[int]) -> int:\n nset=set() # To maintain the bits that are still unset.\n yes=[0]*28 # To check if kth bit is set or not.\n for i in range(28):\n nset.add(i) #initially all of the 28 bits are unset.\n\n for i in nums:\n x=[] #Maintain all bits that were previously unset but were set in this number.\n for k in nset:\n if i & (1 << (k)):\n yes[k]=1 #set the kth\n x.append(k)\n #Now remove all the newly set bits from nset(not set yet).\n for k in x:\n nset.remove(k)\n #Now just convert the yes array into a number.\n x=0\n c=1\n for i in yes:\n if i:\n x+=c\n c=c<<1 \n return x\n``` | 2 | 0 | ['Python'] | 0 |
maximum-xor-after-operations | javascript greedy two solutions OR of All 86ms + check ith bit 204ms | javascript-greedy-two-solutions-or-of-al-fn38 | key point: make each i\'th bit only has one 1\'s\n\nconst maximumXOR = (a) => {\n let res = 0;\n for (const x of a) res |= x;\n return res;\n};\n\nSolu | henrychen222 | NORMAL | 2022-06-25T16:14:24.659132+00:00 | 2022-06-25T17:52:57.428065+00:00 | 106 | false | key point: make each i\'th bit only has one 1\'s\n```\nconst maximumXOR = (a) => {\n let res = 0;\n for (const x of a) res |= x;\n return res;\n};\n```\nSolution 2: check each bit if it has one, has, add the mask value to res\n204ms\n```\nconst bit = 27; // cover 10 ^ 8\nconst checkIthBit = (x, i) => x & (1 << i);\n\nconst maximumXOR = (a) => {\n let res = 0;\n for (let i = 0; i < bit; i++) {\n let hasOne = 0;\n for (const x of a) {\n if (checkIthBit(x, i)) hasOne++;\n }\n if (hasOne) res += 1 << i; // add mask 1 << i\n }\n return res;\n};\n```\nSolution 3: same as Solution 2, but using binary string instead\n543ms\n```\nconst fillLeading = (len, s) => \'0\'.repeat(len - s.length) + s;\n\nconst maximumXOR = (a) => {\n let len = 0, res = 0;\n a = a.map(x => {\n let s = x.toString(2);\n len = Math.max(len, s.length);\n return s;\n }).map(s => fillLeading(len, s));\n for (let i = len - 1, bit = 0; ~i; i--, bit++) { // traverse binary string low(right) -> high(left)\n let hasOne = false;\n for (const s of a) {\n if (s[i] == \'1\') hasOne = true;\n }\n if (hasOne) res += 1 << bit;\n }\n return res;\n};\n``` | 2 | 0 | ['Bit Manipulation', 'JavaScript'] | 0 |
maximum-xor-after-operations | C++ | Bit manipulation | c-bit-manipulation-by-amirkpatna-c20w | \nclass Solution {\npublic:\n int maximumXOR(vector<int>& v) {\n vector<bool> cnt(31);\n for(int x:v){\n int i=0;\n for(i | amirkpatna | NORMAL | 2022-06-25T16:01:52.103149+00:00 | 2022-06-25T16:08:03.665994+00:00 | 220 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& v) {\n vector<bool> cnt(31);\n for(int x:v){\n int i=0;\n for(int i=0;x;i++){\n if(x&1)cnt[i]=true;\n x>>=1;\n }\n }\n int ans=0;\n for(int i=0;i<31;i++){\n if(cnt[i])\n ans+=(1<<i);\n }\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
maximum-xor-after-operations | ✔ Python3 Solution | O(n) | python3-solution-on-by-satyam2001-n3zs | Time : O(n)\nSpace : O(1)\n\n\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n res = 0\n for i in nums:\n res |= i | satyam2001 | NORMAL | 2022-06-25T16:01:50.925032+00:00 | 2022-06-25T16:01:50.925078+00:00 | 221 | false | ```Time``` : ```O(n)```\n```Space``` : ```O(1)```\n\n```\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n res = 0\n for i in nums:\n res |= i\n return res\n``` | 2 | 0 | ['Python'] | 1 |
maximum-xor-after-operations | O(1) Solution with simple approach | C++ | explained | o1-solution-with-simple-approach-c-expla-psqm | We can make change 1 to 0 but can\'t change 0 to 1 in num[i]\n 2. ( n&(n^x) ) => ith bit of n is 0 zero then it will be zero always ans & operation is fina | aynburnt | NORMAL | 2022-06-25T16:00:52.989366+00:00 | 2022-06-25T16:04:14.249934+00:00 | 183 | false | 1. We can make change 1 to 0 but can\'t change 0 to 1 in num[i]\n 2. ( n&(n^x) ) => ith bit of n is 0 zero then it will be zero always ans & operation is final operation\n=> **so count for every bit if at least 1 set bit is there then take it into answer;**\n```\nint maximumXOR(vector<int>& nums) {\n int ans = 0;\n for(int i=0; i<32; i++){\n int tmp = (1<<i);\n int flag=0;\n for(auto x : nums){\n if((x&tmp)){\n flag = 1;\n break;\n }\n }\n if(flag)ans += tmp;\n }\n return ans;\n }\n``` | 2 | 0 | ['C++'] | 0 |
maximum-xor-after-operations | C++ | Easy Solution | 12 Lines of Code | c-easy-solution-12-lines-of-code-by-char-txry | \nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int x_or = 0;\n for(int i=31;i>=0;i--)\n {\n for(auto x:n | charitramehlawat | NORMAL | 2022-06-25T16:00:43.764004+00:00 | 2022-06-25T16:06:24.967557+00:00 | 195 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int x_or = 0;\n for(int i=31;i>=0;i--)\n {\n for(auto x:nums)\n {\n if(((x>>i)&1)==1)// If 1 bit is present then all the other ith bits can be disabled using the above given operation and this bit can be taken in our answer to make our answer maximum.\n {\n x_or|= (1<<i);\n break;\n }\n }\n }\n return x_or;\n }\n // UPVOTE if you like\n};\n``` | 2 | 0 | ['C', 'C++'] | 0 |
maximum-xor-after-operations | AAAAAAAAAAAAAAAAAAAAAAAAAAAAA | aaaaaaaaaaaaaaaaaaaaaaaaaaaaa-by-danisde-n54w | Code | DanisDeveloper | NORMAL | 2025-03-14T22:35:09.643822+00:00 | 2025-03-14T22:35:09.643822+00:00 | 11 | false |
# Code
```kotlin []
class Solution {
fun maximumXOR(nums: IntArray): Int {
var result = 0
for(i in nums.indices){
result = result or nums[i]
}
return result
}
}
``` | 1 | 0 | ['Kotlin'] | 0 |
maximum-xor-after-operations | Bitwise OR | Beats 100%, 0ms, C# | bitwise-or-beats-100-0ms-c-by-bkga9sasfa-jscz | ApproachThe operation described in the task lets us delete any set bits in any number. Therefore the maximum XOR, after applying operations, contains a 1 at all | bKGa9sAsfA | NORMAL | 2025-03-06T09:39:47.902483+00:00 | 2025-03-06T09:39:47.902483+00:00 | 13 | false | # Approach
The operation described in the task lets us delete any set bits in any number. Therefore the maximum XOR, after applying operations, contains a 1 at all positions where there exists a number in nums with a 1 at that position. This can be expressed using the bitwise OR.
# Complexity
- Time complexity: $$O(n)$$
- Space complexity: $$O(1)$$
# Code
```csharp []
public class Solution {
public int MaximumXOR(int[] nums) {
int n = 0;
foreach(int num in nums) n |= num;
return n;
}
}
``` | 1 | 0 | ['C#'] | 0 |
maximum-xor-after-operations | 0ms C bit teaser | c-bit-teaser-by-michelusa-r7r2 | Just step back and think we are looking for a maximum from a list of number based on some operation.
The maximum number would be to have as many bits set at one | michelusa | NORMAL | 2025-01-13T13:42:09.777852+00:00 | 2025-01-13T13:42:30.818446+00:00 | 32 | false | Just step back and think we are looking for a maximum from a list of number based on some operation.
The maximum number would be to have as many bits set at one as possible.
That would happen if no bits are eliminated due to XOR, meaning all 1 bits from each number in the array can contributed.
So we OR all numbers and return that result.
# Code
```cpp []
class Solution {
public:
int maximumXOR(vector<int>& nums) {
int or_vector = 0;
for (int val : nums) {
or_vector |= val;
}
return or_vector;
}
};
``` | 1 | 0 | ['C++'] | 0 |
maximum-xor-after-operations | Degrees 2 in the range 0..26 | degrees-2-in-the-range-026-by-sav2001196-2ud4 | Approach\nSo, the premise of the decision:\n1) Any number cannot become greater when the AND operation is performed on it with any other number. \n2) From any n | sav20011962 | NORMAL | 2024-10-09T09:17:11.367205+00:00 | 2024-10-10T05:41:06.631282+00:00 | 14 | false | # Approach\nSo, the premise of the decision:\n1) Any number cannot become greater when the AND operation is performed on it with any other number. \n2) From any number in the array by performing (nums[i] AND (nums[i] XOR x))we can get all numbers from 0 to nums[i].\nThus, the original problem is transformed into the problem of finding all significant positions in all numbers in the array.\nThe first thing that comes to mind to realize this task, and at that the simplest (but hardly the most efficient) algorithmically, is the OR operation between all elements of the array.\nI propose a different solution - I search not the numbers in the array, but the degrees 2 from zero to the maximum according to the constraints of the problem and try for each such value to find the first number in the array that contains a unit in the desired position. To reduce idle operations, I decided to apply a small trick - see in the code.\n\nVAR1\n\n```\nclass Solution {\n fun maximumXOR(nums: IntArray): Int {\n var rez = 0\n // val max = nums.max()\n for (N in arr) {\n // if (N>max) break\n if (nums.firstOrNull { (it and N) == N } != null) rez = rez or N\n }\n return rez\n }\n companion object {\n val arr = IntArray(27) {1 shl it}\n }\n}\n```\nVAR2\n\n```\nclass Solution {\n fun maximumXOR(nums: IntArray): Int {\n var rez = 0\n var N = 1 shl 26\n while (N>=1) {\n if (N and rez != N) {\n val tek = nums.firstOrNull { (it and N) == N }\n if (tek != null) rez = rez or tek\n }\n N = N shr 1\n }\n return rez\n }\n}\n```\nHere is the result of a comparative test of two algorithms - the regular one with OR and mine with degree 2.\nThe tests were performed here, in the sandbox, on the same random arrays of different sizes for both functions:\n\n | 1 | 0 | ['Kotlin'] | 0 |
maximum-xor-after-operations | Python easy solution || Beats 100% 🔥⚡ | python-easy-solution-beats-100-by-asrith-wr7z | Intuition : Bit manipulation\n Describe your first thoughts on how to solve this problem. \n\n# Approach : using OR\n Describe your approach to solving the prob | asritha_chilamakuri | NORMAL | 2024-07-02T10:52:37.824543+00:00 | 2024-07-02T10:52:37.824572+00:00 | 93 | false | # Intuition : Bit manipulation\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach : using OR\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(object):\n def maximumXOR(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n res=0\n for i in nums:\n res=res|i\n return res\n``` | 1 | 0 | ['Python'] | 0 |
maximum-xor-after-operations | BEATS 100% || SIMPLEST AND EASYEST || BITWISE | beats-100-simplest-and-easyest-bitwise-b-h3g9 | 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 | varma7 | NORMAL | 2023-12-04T16:30:52.699408+00:00 | 2023-12-04T16:30:52.699441+00:00 | 165 | 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- O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\nIn question we need maximum xor of all the elements and we are performing or operation for achiving it for every element\nUP VOTE IF YOU UNDERSTAND AND IF IT IS HELPFUL FOR YOU;\n```\nclass Solution{\n public int maximumXOR(int [] nums){\n int ans=0;\n for(int i:nums){\n ans=ans|i;\n }\n return ans;\n }\n}\n\n//***********ANOTHER METHOD**************** */\n// class Solution {\n// public int maximumXOR(int[] nums) {\n// int len=nums.length;\n// boolean b[]=new boolean[32];\n// for(int i:nums){\n// int n=i;\n// int index=0;\n// while(n>0){\n// if((n&1)!=0){\n// b[index]=true;\n// }\n\n// n=n>>1;\n// index++;\n// }\n// }\n// int ans=0;\n// for(int i=0;i<32;i++){\n// if(b[i]){\n// ans+=1<<i;\n// }\n// }\n// return ans;\n// }\n// }\n``` | 1 | 0 | ['Java'] | 1 |
maximum-xor-after-operations | Beats 100%🔥|| 3 Lines🔥|| easy JAVA Solution✅ | beats-100-3-lines-easy-java-solution-by-geei1 | how can we get the maximum number simply by setting every possible bit to 1 and how can we do it simple by using OR.\n# Code\n\nclass Solution {\n public int | priyanshu1078 | NORMAL | 2023-12-01T10:12:13.872305+00:00 | 2023-12-01T10:12:13.872321+00:00 | 10 | false | how can we get the maximum number simply by setting every possible bit to 1 and how can we do it simple by using OR.\n# Code\n```\nclass Solution {\n public int maximumXOR(int[] nums) {\n int ans=0;\n for(int i:nums) ans|=i;\n return ans;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
maximum-xor-after-operations | Java O(N) solution | java-on-solution-by-shree_govind_jee-65jz | 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 | Shree_Govind_Jee | NORMAL | 2023-11-23T04:55:46.871446+00:00 | 2023-11-23T04:55:46.871470+00:00 | 27 | false | # 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 {\n public int maximumXOR(int[] nums) {\n int res = 0;\n for(int num:nums){\n res |= num;\n }\n return res;\n }\n}\n``` | 1 | 0 | ['Array', 'Math', 'Bit Manipulation', 'Java'] | 1 |
maximum-xor-after-operations | Copied solution but tried to explain in a better way | copied-solution-but-tried-to-explain-in-kb9dq | Intuition\nWhat does a&(a^b) do?\nIt says that whatever bit of a is different from that of b, keep it. Turn all other bits to 0.\n\nThose different bits will an | AT_01 | NORMAL | 2023-08-05T07:14:45.826108+00:00 | 2023-08-05T07:14:45.826134+00:00 | 9 | false | # Intuition\nWhat does a&(a^b) do?\nIt says that whatever bit of a is different from that of b, keep it. Turn all other bits to 0.\n\nThose different bits will anyway produce 1 when XORed. \n\nThe bits that were same as that of b are now 0. These bits were either 0 or 1 in b. If they were 1, they are now 0, and will produce 1 when XORed. \n\nRepeating the same operation on a again with b as x shall cause no change in a.\n\n\nAlso please note that bits that are 0 in both a and b will never tranform to 1 with any number of operation between a nd b.\n\nHence the intuition. \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)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) \n {\n int res = 0;\n for (int a: nums)\n res |= a;\n return res;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximum-xor-after-operations | Easy Solution C++| 3 lines | easy-solution-c-3-lines-by-bajpayiananya-spxm | 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 | bajpayiananya | NORMAL | 2023-06-26T07:50:28.958895+00:00 | 2023-06-26T07:50:28.958923+00:00 | 213 | 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 int maximumXOR(vector<int>& nums) {\n int n=0;\n for(int i=0;i<nums.size();i++)\n {\n n=n|nums[i];\n }\n return n; \n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximum-xor-after-operations | since we can't make one by ourselves, doing OR between them will give the answer | since-we-cant-make-one-by-ourselves-doin-lzx7 | \nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int res = 0;\n for(auto i : nums)\n res|=i;\n return res; | mr_stark | NORMAL | 2023-03-28T13:06:27.492678+00:00 | 2023-03-28T13:06:27.492712+00:00 | 493 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int res = 0;\n for(auto i : nums)\n res|=i;\n return res;\n }\n};\n``` | 1 | 1 | ['C'] | 0 |
maximum-xor-after-operations | C++ Simple Implementation using (BITWISE OR) | c-simple-implementation-using-bitwise-or-bfsb | \n\n# Code\n\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans=0;\n for(auto x:nums){\n ans= ans | x;\n | ayushnautiyal1110 | NORMAL | 2023-03-27T10:56:31.604651+00:00 | 2023-03-27T10:56:31.604694+00:00 | 372 | false | \n\n# Code\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans=0;\n for(auto x:nums){\n ans= ans | x;\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Bit Manipulation', 'C++'] | 0 |
maximum-xor-after-operations | C++ || Explained || O(N) || 3 lines code || Bit manipulation | c-explained-on-3-lines-code-bit-manipula-ahbs | Algorithm\n\n\n- Here we need to find the maximum xor of an array and we can replace a number a by a & ( a ^ x) where x is a non negative number \n- What does | siddhantk1103 | NORMAL | 2022-09-15T12:40:36.298800+00:00 | 2022-09-15T12:40:36.298839+00:00 | 247 | false | __Algorithm__\n\n\n- Here we need to find the maximum xor of an array and we can replace a number a by a & ( a ^ x) where x is a non negative number \n- What does a & ( a ^ x) mean ? Suppose you have 2 numbers in array 1 and 3\n``` \n 1 -> 0 0 0 1\n\t\t\t\t\t\t 3 -> 0 0 1 1\n```\n- Now the xor operation is a odd ones detector and xor of 1 and 3 is 2 as at 0 th bit there are 2 1\'s so looking at a & ( a ^ x) carefully we understand it can be used to make a bit which is 1 in binary representation 0 __but not 0 to 1__\n- Now we see that the max number will have 1 is 0th bit if any number in array will have 1 in its 0 th bit as if there are other numbers with 1 in 0th bit at there sum is even we can make it odd by using the a & ( a ^ x) operation\n- So answer will be just or of all numbers it ith bit is 1 if any number in array has a ith bit 1\n\n__Code__\n```cpp\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans =0 ;\n for(auto a : nums) ans |= a;\n return ans;\n }\n};\n``` | 1 | 0 | ['Bit Manipulation', 'C', 'C++'] | 0 |
maximum-xor-after-operations | Python3 very easy | python3-very-easy-by-excellentprogrammer-wvnr | \nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n s=[nums[0]]\n for i in range(len(nums)):\n s.append(s[-1]|nums[i | ExcellentProgrammer | NORMAL | 2022-08-31T10:19:38.503417+00:00 | 2022-08-31T10:19:38.503455+00:00 | 83 | false | ```\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n s=[nums[0]]\n for i in range(len(nums)):\n s.append(s[-1]|nums[i])\n return max(s)\n``` | 1 | 0 | [] | 0 |
maximum-xor-after-operations | Python one liner with explanation | python-one-liner-with-explanation-by-nik-adxd | The operation\nnums[i] = nums[i] & (nums[i] ^ x)\neffectively turns off any bit 1 in nums[i].\nIt cannot turn on 1, so we can only remove any 1 bits that are al | nikamir | NORMAL | 2022-08-27T23:59:13.099121+00:00 | 2022-08-27T23:59:13.099166+00:00 | 58 | false | The operation\nnums[i] = nums[i] & (nums[i] ^ x)\neffectively turns off any bit 1 in nums[i].\nIt cannot turn on 1, so we can only remove any 1 bits that are already in the array.\nThis way we can always create a combination of odd 1 in any position as long as there is 1 at that position at any number.\nThus, just bundle all numbers with 1 in their position with | (or) and done.\n\n```\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n return reduce(operator.or_, nums)\n``` | 1 | 0 | [] | 0 |
maximum-xor-after-operations | C++ Code || Bit Manipulation | c-code-bit-manipulation-by-girdhar-rxwg | \nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) \n {\n \n int ans = 0;\n \n for(auto it: nums)\n {\ | Girdhar__ | NORMAL | 2022-07-30T16:33:42.888150+00:00 | 2022-07-30T16:38:53.291787+00:00 | 130 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) \n {\n \n int ans = 0;\n \n for(auto it: nums)\n {\n ans = ans | it; \n }\n\n return ans;\n \n }\n};\n``` | 1 | 0 | ['Bit Manipulation', 'C', 'C++'] | 0 |
maximum-xor-after-operations | bitwise or ^^ | bitwise-or-by-andrii_khlevniuk-irx0 | \nint maximumXOR(vector<int>& n)\n{\n\treturn accumulate(begin(n), end(n), 0, bit_or{});\n}\n | andrii_khlevniuk | NORMAL | 2022-07-12T11:40:04.640161+00:00 | 2022-07-12T15:37:26.366024+00:00 | 136 | false | ```\nint maximumXOR(vector<int>& n)\n{\n\treturn accumulate(begin(n), end(n), 0, bit_or{});\n}\n``` | 1 | 0 | ['C', 'C++'] | 0 |
maximum-xor-after-operations | java Easy Explanation | java-easy-explanation-by-shiavm-singh-k2gd | num[i] = nums[i]&(nums[i]^x)\nnums[i] = nums[i]&nums[i]^(nums[i] & x )\nnums[i] = nums[i]^(nums[i]&x)\n\nHere nums[i]&x = only common bit between x and nums[i] | shiavm-singh | NORMAL | 2022-07-11T12:43:41.588621+00:00 | 2022-07-11T12:43:41.588672+00:00 | 92 | false | num[i] = nums[i]&(nums[i]^x)\nnums[i] = nums[i]&nums[i]^(nums[i] & x )\nnums[i] = nums[i]^(nums[i]&x)\n\nHere nums[i]&x = only common bit between x and nums[i] will be there other will be gone.\nFor example => 1001&(0101) = 0001\n\n* We conclude that any set bit can be can 0, using this operation\n* We will calculate bit count at every position upto 32 bits, and if it is 0, then we can\'t do anything, but if it is odd we will leave it\n* but it is Even, this operation to remove 1 set bit to make it Odd, so that this set bit at this position can contribute of our Ans.\n\n0011\n0010\n0011\n0010\n1001\n-----\n1 2 3 4 \nHere at 2nd postion set bit count is zero, so we can\'t do anything, \nbut at 3rd position set bit count in even, so we can make it Odd using operation, \n***That is the use of this operation to remove a set bit. \n```*\nclass Solution {\n public int maximumXOR(int[] nums) {\n // N\n // 3 = 11\n // 4 = 100\n // 6 = 110\n int n = nums.length;\n int[][] arr = new int[n][32];\n \n for(int i = 0; i < n; i++){\n int ele = nums[i];\n for(int j = 0; j < 32; j++){\n if(((ele >> j)&1) == 1){\n arr[i][j] = 1;\n }else{\n arr[i][j] = 0;\n }\n }\n }\n \n long ans = 0;\n for(int i = 0; i < 32; i++){\n int cnt = 0;\n for(int j = 0; j < n; j++){\n if(arr[j][i] == 1) cnt++;\n }\n if(cnt == 0) continue;\n \n ans += (1 << i);\n }\n \n return (int)ans;\n }\n}\n``` | 1 | 0 | [] | 0 |
maximum-xor-after-operations | Java O(n) easy, simple, and straight forward solution | java-on-easy-simple-and-straight-forward-nq5y | \nclass Solution {\n public int maximumXOR(int[] nums) {\n int max = 0;\n for(int num: nums)\n max = max | num;\n return max; | foolish-engineer | NORMAL | 2022-06-28T14:22:26.094191+00:00 | 2022-06-28T14:22:26.094226+00:00 | 51 | false | ```\nclass Solution {\n public int maximumXOR(int[] nums) {\n int max = 0;\n for(int num: nums)\n max = max | num;\n return max;\n }\n}\n``` | 1 | 0 | [] | 1 |
maximum-xor-after-operations | 🔥 C++ Detailed Explanation | Easy Approach | c-detailed-explanation-easy-approach-by-ayha0 | \uD83D\uDCCDKindly Upvote, It is FREE from your side\n\n\uD83D\uDD25Approach:-\n Whenever we are doing nums[i] = nums[i] & (nums[i] ^ x). Please note that the A | AlphaDecodeX | NORMAL | 2022-06-28T06:48:39.444072+00:00 | 2022-06-28T06:48:39.444116+00:00 | 86 | false | \uD83D\uDCCD**Kindly Upvote, It is FREE from your side**\n\n\uD83D\uDD25Approach:-\n* Whenever we are doing nums[i] = nums[i] & (nums[i] ^ x). Please note that the And operation will produce the result 0 if any bit of the number is zero.\n* It can produce 1/0 depending on the result of nums[i]^x. Because XOR operator can produce 1/0 depending on the x.\n* Whenever we XOR all the numbers at the end. If at any bit we have a minimum of one 1 from all the numbers It means that bit can be converted to 1.\n* Refer to YouTube for more detailed explanation.\n\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans = 0;\n int isSet = 0;\n \n for(int i = 31; i>=0; i--){\n isSet = 0;\n for(auto &x: nums){\n if(x&(1<<i)){\n isSet = 1;\n break;\n }\n }\n if(isSet){\n ans = ans | (1<<i);\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['Bit Manipulation', 'C', 'C++'] | 0 |
maximum-xor-after-operations | Didn't expect it as medium. 2 liner solution in C++ | didnt-expect-it-as-medium-2-liner-soluti-b5jb | \nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums){\n int xorr = 0;\n for(auto it : nums) xorr |= it;\n return xorr;\n }\n} | NextThread | NORMAL | 2022-06-27T15:15:13.871126+00:00 | 2022-06-27T15:15:13.871173+00:00 | 19 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums){\n int xorr = 0;\n for(auto it : nums) xorr |= it;\n return xorr;\n }\n};\n``` | 1 | 0 | ['C'] | 0 |
maximum-xor-after-operations | C++ | Easy Simple Approach | Beginners Friendly | c-easy-simple-approach-beginners-friendl-o00d | \nint maximumXOR(vector<int>& nums) {\n int ans=0;\n for(int i=0;i<nums.size();i++)\n ans=ans|nums[i];\n return ans;\n }\n | aaquilnasim | NORMAL | 2022-06-26T14:36:25.965093+00:00 | 2022-06-26T14:36:25.965135+00:00 | 91 | false | ```\nint maximumXOR(vector<int>& nums) {\n int ans=0;\n for(int i=0;i<nums.size();i++)\n ans=ans|nums[i];\n return ans;\n }\n``` | 1 | 0 | ['Bit Manipulation', 'C', 'C++'] | 0 |
maximum-xor-after-operations | I can't believe it work !! | i-cant-believe-it-work-by-zhuangzhutao-y0my | My idea \n\nI thought it would take little bit extra time to solve the third problem of the weekly contest.\n\nBut I was wrong.\n\nI missed the opportunity of p | zhuangzhutao | NORMAL | 2022-06-26T12:15:18.163887+00:00 | 2022-06-26T12:15:18.163915+00:00 | 29 | false | ## My idea \n\nI thought it would take little bit extra time to solve the third problem of the weekly contest.\n\nBut I was wrong.\n\nI missed the opportunity of passing another problem in the contest yesterday during contest.\n\nI read the problem more carefully today.\n\nThe problem states that the operation is number AND (number XOR x) ,\nwhich means you can not add extra one bit to a number but only decrease the \nnumber of one bit for one number.\n\n\nSo I know that what we need to do is to keep as much as one bit in the final number .\n\nSo I guess we could just using OR operation to all numbers in the array,\nand this is the biggest number we can get.\n\nAnd it pass. AC !! \n\nI can\'t believe it .\n\nAnd you and I should check out the @lee215 for formal prove of this algorithm .\n\n\n## My code \n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int res = 0;\n for(int num: nums) {\n res = res | num;\n }\n \n return res;\n }\n};\n```\n | 1 | 0 | [] | 1 |
maximum-xor-after-operations | Go | Golang | Explanation | O(n) | go-golang-explanation-on-by-camusabsurdo-pff5 | ```\nfunc maximumXOR(nums []int) (ans int) { \n /\n So suppose after doing xor [3,2,4,6] we\'re getting 3\n\n 3 => 0 0 1 1\n 2 => 0 | camusabsurdo | NORMAL | 2022-06-26T09:20:07.360839+00:00 | 2022-06-26T09:20:07.360882+00:00 | 31 | false | ```\nfunc maximumXOR(nums []int) (ans int) { \n /*\n So suppose after doing xor [3,2,4,6] we\'re getting 3\n\n 3 => 0 0 1 1\n 2 => 0 0 1 0\n 4 => 0 1 0 0\n 6 => 0 1 1 0\n xor => 0 0 1 1\n \n The xor result can be maximised if either 4 became 0 or 6 became 2 using the operations described. Now the key to notice here is that we actually don\'t need to perform the operations since we are only interested in the maximisation and not the order of operations and that leads us to realise that we can effectively chose to Bitwise OR the elements (instead of the proposed XOR) and our work is done.\n */\n for _,num:=range nums{\n ans |=num\n }\n return\n} | 1 | 0 | ['Go'] | 0 |
maximum-xor-after-operations | Maximum XOR After Operations | maximum-xor-after-operations-by-babu45-51le | \nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n vector<bool>v(32,0);\n for(int i=0;i<nums.size();i++){\n for(int | babu45 | NORMAL | 2022-06-26T05:16:21.687618+00:00 | 2022-06-26T05:16:21.687664+00:00 | 26 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n vector<bool>v(32,0);\n for(int i=0;i<nums.size();i++){\n for(int j=0;j<32;j++)\n if(nums[i]&(1<<j))v[j]=1;\n }\n int ans=0;\n for(int i=0;i<32;i++)\n if(v[i])ans+=pow(2,i);\n \n return ans;\n }\n};\n``` | 1 | 0 | ['Bit Manipulation'] | 0 |
maximum-xor-after-operations | Trie C++ Solution | trie-c-solution-by-rohit_271-cvbh | ```\nclass Solution {\npublic:\n class Node{\n public:\n int x;\n Node left,right;\n Node(){\n left=NULL;\n | rohit_271 | NORMAL | 2022-06-25T20:36:03.950306+00:00 | 2022-06-25T20:36:03.950332+00:00 | 66 | false | ```\nclass Solution {\npublic:\n class Node{\n public:\n int x;\n Node* left,*right;\n Node(){\n left=NULL;\n right=NULL;\n }\n Node(int y){\n x=y;\n left=NULL;\n right=NULL;\n }\n };\n class Trie{\n public:\n Node* root;\n Trie(){\n root=new Node() ; \n }\n void insert(int x){\n Node* temp=root;\n for(int i=30;i>=0;i--){\n if((x>>i)&1){\n if(temp->right)temp=temp->right;\n else{\n temp->right=new Node();\n temp=temp->right;\n }\n }\n else{\n if(temp->left)temp=temp->left;\n else{\n temp->left=new Node();\n temp=temp->left;\n }\n }\n }\n }\n int search(int x){\n Node* temp=root;\n int ans=0;\n for(int i=30;i>=0;i--){\n if((x>>i)&1){\n if(temp->left){\n ans|=(1<<i);\n temp=temp->left;\n }\n else temp=temp->right;\n }\n else{\n if(temp->right){\n ans|=(1<<i);\n temp=temp->right;\n }\n else temp=temp->left;\n }\n }\n return ans;\n }\n };\n int maximumXOR(vector<int>& nums) {\n \n if(nums.size()==1)return nums[0];\n Trie obj;\n int ans=0;\n int pre=0;\n for(int i=0;i<nums.size();i++){\n int x=pre^nums[i];\n obj.insert(x);\n ans=max(ans,obj.search(x));\n pre^=nums[i];\n }\n for(int i=0;i<nums.size();i++){\n obj.insert(nums[i]);\n ans=max(ans,obj.search(nums[i]));\n }\n return ans;\n }\n}; | 1 | 0 | ['Trie'] | 0 |
maximum-xor-after-operations | 2 approaches - Python Easy Understanding | 2-approaches-python-easy-understanding-b-fqsf | \tclass Solution(object):\n\t\tdef maximumXOR(self, nums):\n\t\t\t#approach1\n\t# lis=[0 for _ in range(32)]\n\t# for i in range(32):\n\t# | prateekgoel7248 | NORMAL | 2022-06-25T19:31:59.345540+00:00 | 2022-06-25T19:31:59.345572+00:00 | 73 | false | \tclass Solution(object):\n\t\tdef maximumXOR(self, nums):\n\t\t\t#approach1\n\t# lis=[0 for _ in range(32)]\n\t# for i in range(32):\n\t# for j in nums:\n\t# if 1<<i & j:\n\t# lis[i]=1\n\t# break\n\t# s=0\n\t# val=1\n\n\t# for i in range(32):\n\t# if lis[i]:\n\t# s+=val\n\t# val*=2\n\t# return s\n\n\t#approach2\n\t#as we know we have to find the xor of all the elements\n\t#so we can observe there that we are calculating the sum only(of the odd bits)\n\t#lets take example\n\t#[3,2,4,6]\n\t#3-0011\n\t#2-0010\n\t#4-0100\n\t#6-0110\n\t#so we have to find only odd bit sum\n\t#so we make the 6th 3rd bit 0 to make the odd bit at the 3rd position\n\t#and we know that if there exist 1 in any number at that position then we can make others 0 and take the first one to make the odd\n\t#so here we are taking the or (which will take only the set bits - as we know 0 or 0 means 0 and 1 for all other cases)\n\t\t\tr = 0\n\t\t\tfor num in nums:\n\t\t\t\tr |= num\n\t\t\treturn r\n\n\t\t\t"""\n\t\t\t:type nums: List[int]\n\t\t\t:rtype: int\n\t\t\t"""\n | 1 | 0 | ['Python', 'C++', 'Python3'] | 2 |
maximum-xor-after-operations | Python solution O(n) time O(1) space | python-solution-on-time-o1-space-by-robe-skb9 | If you haven\'t tried \nhttps://leetcode.com/problems/single-number/ [easy]\nyet that is a good warm up problem to this one. My description uses similar reasoni | roberluc | NORMAL | 2022-06-25T18:41:15.836959+00:00 | 2022-06-25T18:42:17.652355+00:00 | 119 | false | If you haven\'t tried \nhttps://leetcode.com/problems/single-number/ [easy]\nyet that is a good warm up problem to this one. My description uses similar reasoning. \n\nIn particular checkout the solution # 6: Sum of Set Bits \n\nTo arrive at the solution observe two things:\n\n(1) nums[0] XOR nums[1] XOR ... XOR nums[n-1] will be the number of \n*odd* set bit sums when we sum by ith bit index. \n(2) The way that the AND operation works with the XOR is such that you can flip any and as many or as few bits you like. e.g. `6 & (4^6)` is the same as `110 & (100^110) = 110 & 010 = 010` and this last value is 2 in base 10 representation. The key point in the problem statement is that `x` can be *any* value so we choose the value that flips the necessary bit to make this column sum to an *odd* number instead of the *even* we currently have. \n\nIf we do the bit position sum for all the values and then the operation in (2) for all the even sums we\'ll be left with all odd sums where there was a set bit in *at least one of the numbers* in the ith position.\n\nNow we don\'t care which num in `nums` gave us this set bit this is the same as an `OR` on each value into a set bit accumulator. This gives us:\n```\ndef maximumXOR(nums: List[int]) -> int:\n r = 0\n for num in nums:\n r |= num\n return r\n```\n\n\nAlso a couple more using the bit manipulation approach described here:\nhttps://leetcode.com/problems/missing-number/ [easy]\nhttps://leetcode.com/problems/single-number-ii/ [medium]\n https://leetcode.com/problems/find-the-duplicate-number/ [medium]\n | 1 | 0 | ['Bit Manipulation', 'Python3'] | 0 |
maximum-xor-after-operations | C++ || Easy O(n) || OR | c-easy-on-or-by-hrishilamdade-llnp | \nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int res=0;\n for(auto i:nums){\n res|=i;\n }\n ret | hrishilamdade | NORMAL | 2022-06-25T18:39:12.540904+00:00 | 2022-06-25T18:39:12.540946+00:00 | 58 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int res=0;\n for(auto i:nums){\n res|=i;\n }\n return res;\n }\n};\n``` | 1 | 0 | ['Bit Manipulation', 'C', 'C++'] | 0 |
maximum-xor-after-operations | Video Explanation (With Intuition) | video-explanation-with-intuition-by-codi-5mrx | https://www.youtube.com/watch?v=q9HXx63DZCU | codingmohan | NORMAL | 2022-06-25T18:27:45.076850+00:00 | 2022-06-25T18:27:45.076896+00:00 | 22 | false | https://www.youtube.com/watch?v=q9HXx63DZCU | 1 | 0 | [] | 0 |
maximum-xor-after-operations | C++ || Easy to understand || Beats 100% | c-easy-to-understand-beats-100-by-akshar-8h15 | \nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans=0; \n for(int & a: nums) ans|=a;\n return ans;\n }\n};\n/**\ | aksharma071 | NORMAL | 2022-06-25T17:47:40.356604+00:00 | 2022-06-25T17:47:40.356642+00:00 | 19 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans=0; \n for(int & a: nums) ans|=a;\n return ans;\n }\n};\n/**\nif(find helpful) {\ndo upvote(); // thanks:)\n}\n*/\n``` | 1 | 1 | ['Bit Manipulation', 'C'] | 0 |
maximum-xor-after-operations | JS | Reduce | 1-liner | js-reduce-1-liner-by-escaroda-34wy | \n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maximumXOR = function(nums) {\n return nums.reduce((acc, cur) => acc |= cur, 0);\n};\n | escaroda | NORMAL | 2022-06-25T17:24:51.544024+00:00 | 2022-06-25T17:24:51.544112+00:00 | 131 | false | ```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maximumXOR = function(nums) {\n return nums.reduce((acc, cur) => acc |= cur, 0);\n};\n``` | 1 | 0 | ['JavaScript'] | 0 |
maximum-xor-after-operations | C++ || Simple Code || OR operation | c-simple-code-or-operation-by-theblackho-6lad | ```\nclass Solution {\npublic:\n int maximumXOR(vector& a)\n {\n int n=a.size();\n \n if(n==1) return a[0];\n \n int an | theblackhoop | NORMAL | 2022-06-25T17:14:10.216544+00:00 | 2022-06-25T17:14:10.216574+00:00 | 14 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& a)\n {\n int n=a.size();\n \n if(n==1) return a[0];\n \n int ans=a[0];\n for(int i=1;i<n;i++)\n {\n ans=ans|a[i];\n }\n return ans;\n }\n};\n | 1 | 0 | [] | 0 |
maximum-xor-after-operations | Simple explanation: take OR of all elements | simple-explanation-take-or-of-all-elemen-cdpw | Explanation \nWe can unset or set any bit in A[i] by doing A[i]^x. As we can take same or reverse of that bit in x to unset or set the bit.\nBut in every operat | theesoteric | NORMAL | 2022-06-25T16:49:34.964017+00:00 | 2022-06-25T16:50:54.055390+00:00 | 89 | false | Explanation \nWe can unset or set any bit in A[i] by doing A[i]^x. As we can take same or reverse of that bit in x to unset or set the bit.\nBut in every operation, we also have to do AND with A[i] so we can\'t set any new bit in the result of one operation.\nBut still we can unset any bit in any A[i] with one operation.\nNow we can take every bit as set in the final answer if its set in any of the A[i]. To do so, we can unset the corresponding bit in rest of all numbers of the array except for A[i]. By proving this we can take final answer as OR of all the number of the array.\n\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maximumXOR = function(nums) {\n let ans=0;\n for(let i=0;i<nums.length;i++){\n ans |= nums[i];\n }\n return ans;\n};\n``` | 1 | 0 | ['JavaScript'] | 0 |
maximum-xor-after-operations | Very simple understandable solution with explanations | very-simple-understandable-solution-with-v4wh | \nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int maxi = nums[0];\n int n = nums.size();\n for(int i=1;i<n;i++){\n | yogesh358 | NORMAL | 2022-06-25T16:19:32.193672+00:00 | 2022-06-25T16:19:32.193715+00:00 | 45 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int maxi = nums[0];\n int n = nums.size();\n for(int i=1;i<n;i++){\n maxi=maxi | nums[i];\n }\n return maxi;\n \n }\n};\n``` | 1 | 1 | ['C', 'Python', 'Java'] | 0 |
maximum-xor-after-operations | C++ simple solution | c-simple-solution-by-rupesh_dharme-79r8 | \nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int orr = 0;\n for (auto num : nums) orr |= num;\n return orr;\n | rupesh_dharme | NORMAL | 2022-06-25T16:11:38.711452+00:00 | 2022-06-25T16:11:38.711491+00:00 | 28 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int orr = 0;\n for (auto num : nums) orr |= num;\n return orr;\n }\n};\n``` | 1 | 0 | [] | 0 |
maximum-xor-after-operations | Intuition Explained in Detail | Observation | intuition-explained-in-detail-observatio-n0w1 | \nThe answer is simply bitwise OR of whole array.\n\nBut how do we observe this ?\n\nAs we can replace nums[i] with nums[i] & (nums[i] ^ x)\nThere are only 4 po | bitmasker | NORMAL | 2022-06-25T16:09:31.150384+00:00 | 2022-06-25T16:22:07.195319+00:00 | 90 | false | <br/>\nThe answer is simply bitwise OR of whole array.\n\n**But how do we observe this ?**\n\nAs we can replace nums[i] with nums[i] & (nums[i] ^ x)\nThere are only 4 possible combinations of 0s and 1s, so let\'s see what happens in all cases if we subtitute nums[i] with the above formula\n\n<pre>\nnums[i] = 1 1 0 0\nx = 0 1 0 1\nnums[i] ^ x = 1 0 0 1\nnums[i] & (nums[i] ^ x) = 1 0 0 0\n</pre>\n\nAs you can see from above example by this subtitution, we can get 1 as result only if the bit in nums[i] was 1, if it\'s 0, we cannot make it 1 in anyway\nAs we are not concerned about value of x and just final result, we can make sure that we will make subtituions such that the xor of ith bit of all numbers is 1\nSo, we can make all such bits 1 which is not 0 in all elements of nums[i]\n<br/>\n\n**Intuitive code:**\n\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans = 0;\n for(int i = 0; i < 32; i++) {\n int ones = 0, zeros = 0;\n for(int& num: nums) {\n if((num >> i) & 1) ones++;\n else zeros++;\n }\n if(zeros != nums.size()) ans |= (1 << i);\n }\n return ans;\n }\n};\n```\n\n**Optimised code:**\n\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int ans = 0;\n for(int num: nums) {\n ans |= num;\n }\n return ans;\n }\n};\n```\n\n<br/> | 1 | 0 | ['Bit Manipulation', 'C'] | 0 |
maximum-xor-after-operations | 6105. Maximum XOR After Operations | Bitwise OR | 6105-maximum-xor-after-operations-bitwis-6hfm | \nclass Solution {\n public int maximumXOR(int[] nums) {\n int[] bits=new int[32];//usigned int\n for(int x:nums){\n for(int i=0;i<3 | Ayushman_18 | NORMAL | 2022-06-25T16:09:16.604428+00:00 | 2022-06-25T16:09:25.988650+00:00 | 18 | false | ```\nclass Solution {\n public int maximumXOR(int[] nums) {\n int[] bits=new int[32];//usigned int\n for(int x:nums){\n for(int i=0;i<32;i++){//count 1 at each bit positon!\n if((1&(x>>i))==1)\n bits[i]=1;\n }\n }\n long ans=0L;\n for(int i=0;i<32;i++)\n ans+=(bits[i]==1)?(1<<i):0;//sum of that bit position that hit 1 | max \n return (int)ans;\n }\n}\n//or simply do BITWISE OR of the GIVEN Elements in the Array!\n``` | 1 | 0 | ['Array', 'Bit Manipulation'] | 0 |
maximum-xor-after-operations | 3 line code || c++ | 3-line-code-c-by-jainss-355d | \nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int num=0;\n for(auto it:nums)\n num |=it;\n return num;\ | jainss | NORMAL | 2022-06-25T16:07:15.543286+00:00 | 2022-06-25T16:07:15.543361+00:00 | 27 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int num=0;\n for(auto it:nums)\n num |=it;\n return num;\n }\n};\n``` | 1 | 0 | ['Bit Manipulation'] | 0 |
maximum-xor-after-operations | Python | One Line Solution | O(n) | With Explanation | python-one-line-solution-on-with-explana-mxsx | If we try the "nums[i] AND (nums[i] XOR x)" operation, we get to know that this operation can be used to unset bits of a number. If we want the max XOR, then we | arjuhooda | NORMAL | 2022-06-25T16:06:59.802397+00:00 | 2022-06-25T16:06:59.802479+00:00 | 119 | false | If we try the "nums[i] AND (nums[i] XOR x)" operation, we get to know that this operation can be used to unset bits of a number. If we want the max XOR, then we want 1 at each possible place (if there is atleast one set bit at this place in any number). This definition seems familiar.\nYess !! This is nothing but OR operation. \nUsing the given operation, we can make result as OR operation. \n```\nfrom functools import reduce\nclass Solution:\n def maximumXOR(self, nums: List[int]) -> int:\n return reduce(lambda a,b : a|b, nums)\n`` | 1 | 0 | ['Bit Manipulation', 'Python', 'Python3'] | 0 |
maximum-xor-after-operations | Very Easy to Understand Code [counting bits] | very-easy-to-understand-code-counting-bi-zc53 | ```\nclass Solution {\npublic:\n int maximumXOR(vector& nums) {\n vectorfreq(31,0);\n for(auto x: nums)\n {\n for(int i=0;i<3 | mahakrawat | NORMAL | 2022-06-25T16:03:35.403173+00:00 | 2022-06-25T16:05:19.859362+00:00 | 36 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n vector<int>freq(31,0);\n for(auto x: nums)\n {\n for(int i=0;i<31;i++)\n {\n freq[i]+=(x&(1<<i))?1:0;\n }\n }\n int ans=0;\n for(int i=0;i<31;i++)\n {\n ans+=(freq[i]!=0)?1<<i:0;\n }\n return ans;\n }\n}; | 1 | 0 | ['C'] | 0 |
maximum-xor-after-operations | Simple O(n) TC and O(1) SC solution | simple-on-tc-and-o1-sc-solution-by-parth-jfzu | For any bit that is on in any number that bit will be also on in the answer. So simply find all the possible on bits\n\nclass Solution {\npublic:\n int binar | parth511 | NORMAL | 2022-06-25T16:03:10.619946+00:00 | 2022-06-25T16:03:10.619990+00:00 | 24 | false | For any bit that is on in any number that bit will be also on in the answer. So simply find all the possible on bits\n```\nclass Solution {\npublic:\n int binaryToDecimal(string n){\n string num = n;\n int dec_value = 0, base = 1, len = num.length();\n for (int i = len - 1; i >= 0; i--) {\n if (num[i] == \'1\')\n dec_value += base;\n base = base * 2;\n }\n return dec_value;\n }\n int maximumXOR(vector<int>& nums) {\n vector<int> v(33, 0);\n for(auto num : nums){\n int count = 0;\n while(num){\n if(num % 2 == 1) v[count] = 1;\n num /= 2;\n count++;\n }\n }\n string ans = "";\n for(int i = 0; i < 30; ++i){\n ans = to_string(v[i]) + ans;\n }\n return binaryToDecimal(ans);\n }\n};\n``` | 1 | 0 | ['Math', 'C', 'Iterator'] | 0 |
maximum-xor-after-operations | Simple OR | simple-or-by-cdev-eujq | \n public int MaximumXOR(int[] nums) \n {\n int result = 0;\n foreach (var num in nums)\n result |= num;\n return result;\ | CDev | NORMAL | 2022-06-25T16:02:16.836895+00:00 | 2022-06-25T16:14:41.914653+00:00 | 110 | false | ```\n public int MaximumXOR(int[] nums) \n {\n int result = 0;\n foreach (var num in nums)\n result |= num;\n return result;\n }\n``` | 1 | 0 | [] | 0 |
maximum-xor-after-operations | Easy C++ Solution | O(N) | With Explaination | easy-c-solution-on-with-explaination-by-4ujk9 | OBSERVATION : The main observaton is that we can not set any bit of any element in nums. We can only set off.\nSo the optimal way will be to keep a bit on in ex | Roar47 | NORMAL | 2022-06-25T16:01:12.740511+00:00 | 2022-06-25T16:01:12.740540+00:00 | 51 | false | **OBSERVATION** : The main observaton is that we can not set any bit of any element in nums. We can only set off.\nSo the optimal way will be to keep a bit on in exactly one element of nums. So that when we take XOR of all elements it will be on in the final answer.\nHere is the implementation.\n```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) \n {\n int n=nums.size(),i,ans=0;\n vector <int> cnt(30);\n for(i=0;i<30;i++)\n {\n for(auto x : nums)\n {\n //count number of element that has ith bit set\n cnt[i]+=((x>>i)&1);\n }\n //if there is atleast one element in nums which has ith bit set\n if(cnt[i]>0)\n {\n //set the ith bit in ans\n ans+=(1<<i);\n }\n }\n return ans;\n }\n}; | 1 | 0 | ['Bit Manipulation', 'C'] | 0 |
maximum-xor-after-operations | leetcode just made you a fool !! | leetcode-just-made-you-a-fool-by-binaykr-hx6i | \nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int mask = 0;\n for(int i=0; i<nums.size(); i++)\n {\n ma | binayKr | NORMAL | 2022-06-25T16:00:58.908909+00:00 | 2022-06-25T16:00:58.908955+00:00 | 82 | false | ```\nclass Solution {\npublic:\n int maximumXOR(vector<int>& nums) {\n int mask = 0;\n for(int i=0; i<nums.size(); i++)\n {\n mask|=nums[i];\n }\n return mask;\n }\n};\n``` | 1 | 1 | [] | 0 |
maximum-xor-after-operations | O(n*32), just check if can we find a number with ith bit set. | on32-just-check-if-can-we-find-a-number-du1tv | Explaination - \nlets say\nxor = n1 ^ n2 ^ .........nN\nwhen this xor can be maximum -> when it has all the bits set.\n\nto have ith bit set in final xor ->\nwe | prabhjyot28 | NORMAL | 2022-06-25T16:00:50.276377+00:00 | 2022-06-25T16:00:50.276410+00:00 | 115 | false | Explaination - \nlets say\nxor = n1 ^ n2 ^ .........nN\nwhen this xor can be maximum -> when it has all the bits set.\n\nto have ith bit set in final xor ->\nwe need to have atleast two numbers from our number set that has opposite ith bit.\n\nnow consider operations, what does it means?\nnums[i] AND (nums[i] XOR x) -> it means, we can turn off any set bit of nums[i].\n\nHow this operation can help us in maximising the final xor?\nSince, we can turn off any set bit from a number that means -> To have ith bit set in our final ans we only need to check if we have one number that has ith bit set. \n\n\n```\ndef canWeFindANumberWithIthBitSet(i):\n mask = 1<<i\n for n in nums:\n if n&mask:\n return True\n return False\n \n ans = \'\'\n for i in range(32, -1, -1):\n ans += \'1\' if canWeFindANumberWithIthBitSet(i) else \'0\'\n return int(ans, base=2)\n \n``` | 1 | 0 | [] | 0 |
maximum-xor-after-operations | Just 4 lines CPP | just-4-lines-cpp-by-about_anuj-0tc8 | \n int maximumXOR(vector<int>& nums) {\n int temp = 0;\n for(auto e: nums) temp |= e;\n return temp;\n }\n | about_anuj | NORMAL | 2022-06-25T16:00:37.497060+00:00 | 2022-06-25T16:00:37.497091+00:00 | 204 | false | ```\n int maximumXOR(vector<int>& nums) {\n int temp = 0;\n for(auto e: nums) temp |= e;\n return temp;\n }\n``` | 1 | 0 | [] | 0 |
maximum-xor-after-operations | Easy to understand java solution | easy-to-understand-java-solution-by-priy-gnd2 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | priyanshuyadav21 | NORMAL | 2025-04-03T17:20:00.114898+00:00 | 2025-04-03T17:20:00.114898+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
```java []
class Solution {
public int maximumXOR(int[] nums) {
int maxxor =0;
for(int i=0;i<nums.length;i++){
maxxor |= nums[i];
}
return maxxor;
}
}
``` | 0 | 0 | ['Java'] | 0 |
maximum-xor-after-operations | Best Approach Or-ing the array to get Maximum XOR JAVA Bit Manipulation | best-approach-or-ing-the-array-to-get-ma-9m7f | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Viraljain_123 | NORMAL | 2025-04-03T11:51:53.571755+00:00 | 2025-04-03T11:51:53.571755+00:00 | 2 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. --> The | (bitwise OR) operation ensures we keep all 1s from any number.
# Approach
<!-- Describe your approach to solving the problem. --> The best approach is simply OR-ing all numbers together to get the highest possible XOR.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ --> O(1)
# Code
```java []
class Solution {
public int maximumXOR(int[] nums) {
int maxXor = 0;
for(int num: nums){
maxXor |= num; // 011 | 010 | 100 | 110 = 111 = 7 max xor use or
}
return maxXor;
}
}
``` | 0 | 0 | ['Java'] | 0 |
maximum-xor-after-operations | OR of all elements | O(n) | 2ms | beating 73.53% | or-of-all-elements-on-2ms-beating-7353-b-cdnn | IntuitionOR of all elementsApproachReduce with OR.Complexity
Time complexity:
O(n)
Space complexity:
O(1)
Code | lilongxue | NORMAL | 2025-03-30T16:30:53.864954+00:00 | 2025-03-30T16:30:53.864954+00:00 | 1 | false | # Intuition
OR of all elements
# Approach
Reduce with OR.
# Complexity
- Time complexity:
O(n)
- Space complexity:
O(1)
# Code
```javascript []
/**
* @param {number[]} nums
* @return {number}
*/
var maximumXOR = function(nums) {
return nums.reduce((acc, cur) => acc | cur)
};
``` | 0 | 0 | ['JavaScript'] | 0 |
maximum-xor-after-operations | OPTIMISED C++ SOL | optimised-c-sol-by-himanshu240504-00wj | IntuitionApproachComplexity
Time complexity:
O(32*N)
Space complexity:
O(1)
Code | himanshu240504 | NORMAL | 2025-03-12T19:38:21.726249+00:00 | 2025-03-12T19:38:21.726249+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:
O(32*N)
- Space complexity:
O(1)
# Code
```cpp []
class Solution {
public:
int maximumXOR(vector<int>& nums) {
vector<int>bits(32,0);
for(int i =0 ;i <nums.size();i++){
for(int j=0;j<32;j++){
int bit = (nums[i]>>j)&1;
bits[j]+=bit;
}
}
int ans =0;
for(int i=0;i<32;i++){
if(bits[i]>0){
ans+= 1LL<<i;
}
}
return ans;
}
};
``` | 0 | 0 | ['C++'] | 0 |
maximum-xor-after-operations | [C] arrOr | Time: O(n), Space: O(1) | c-arror-time-on-space-o1-by-zhang_jiabo-i30d | null | zhang_jiabo | NORMAL | 2025-02-04T14:31:05.487441+00:00 | 2025-02-04T14:31:05.487441+00:00 | 3 | false | ```C []
int arrOr(const int * const nums, const int numsLen){
int result = 0;
for (int i = 0; i < numsLen; i += 1){
result |= nums[i];
}
return result;
}
int maximumXOR(const int * const nums, const int numsLen){
return arrOr(nums, numsLen);
}
``` | 0 | 0 | ['C'] | 0 |
minimum-time-to-make-array-sum-at-most-x | [Java/C++/Python] DP Solution, O(n^2) | javacpython-dp-solution-on2-by-lee215-02vp | Intuition\nThe sa = sum(A), sb = sum(B).\nIf we do nothing,\nwe will have sb * i + sa in total at i seconds.\n\nAt the t seconds,\nwe will select t elements.\nT | lee215 | NORMAL | 2023-08-05T16:27:26.041471+00:00 | 2023-08-13T14:59:26.699940+00:00 | 4,280 | false | # **Intuition**\nThe `sa = sum(A)`, `sb = sum(B)`.\nIf we do nothing,\nwe will have `sb * i + sa` in total at `i` seconds.\n\nAt the `t` seconds,\nwe will select `t` elements.\nTake a look at these selected elements,\n`A[i]` will be removed,\nand the sum for these elements is `b1 * (t - 1) + b2 * (t - 2) .... + bt * 0`.\nso `b1,b2,b3..,bt` are arranged in increasing order.\n<br>\n\n# **Explanation**\nFirstly we sort all pair of `(B[i], A[i])` by value of `B[i]`.\n\nThen we use `dp` to solve this prolem:\n`dp[j][i]` means the maximum value we can reduce at `i` seconds,\nwith `j + 1` step-smallest integers.\n\nThe `dp` equation is\n`dp[j][i] = max(dp[j][i], dp[j - 1][i - 1] + i * b + a)`\nFinally we return sconds `i`,\nif `sb * i + sa - dp[n - 1][i] <= x`,\notherwise return `-1`.\n\nSince we initial `dp[j] = dp[j - 1]`,\nactually we can save the first dimension,\nand improve the space to from `O(n^2)` to `O(n)`\n<br>\n\n# **Complexity**\nTime `O(n^2)`\nSpace `O(n)`\n<br>\n\n**Java**\n```java\n public int minimumTime(List<Integer> A, List<Integer> B, int x) {\n int n = A.size(), sa = 0, sb = 0, dp[] = new int[n + 1];\n List<List<Integer>> BA = new ArrayList<>();\n for (int i = 0; i < n; i++) {\n int a = A.get(i), b = B.get(i);\n BA.add(Arrays.asList(b, a));\n sa += a;\n sb += b;\n }\n Collections.sort(BA, (o1, o2) -> Integer.compare(o1.get(0), o2.get(0)));\n for (int j = 0; j < n; ++j)\n for (int i = j + 1; i > 0; --i)\n dp[i] = Math.max(dp[i], dp[i - 1] + i * BA.get(j).get(0) + BA.get(j).get(1));\n for (int i = 0; i <= n; ++i)\n if (sb * i + sa - dp[i] <= x)\n return i;\n return -1;\n }\n```\n\n**C++**\n```cpp\n int minimumTime(vector<int>& A, vector<int>& B, int x) {\n int n = A.size(), sa = accumulate(A.begin(), A.end(), 0), sb = accumulate(B.begin(), B.end(), 0);\n vector<int> dp(n + 1);\n vector<vector<int>> BA;\n for (int i = 0; i < n; i++)\n BA.push_back({B[i], A[i]});\n sort(BA.begin(), BA.end());\n for (int j = 0; j < n; ++j)\n for (int i = j + 1; i > 0; --i)\n dp[i] = max(dp[i], dp[i - 1] + i * BA[j][0] + BA[j][1]);\n for (int i = 0; i <= n; ++i)\n if (sb * i + sa - dp[i] <= x)\n return i;\n return -1;\n }\n```\n\n**Python**\n```py\n def minimumTime(self, A: List[int], B: List[int], x: int) -> int:\n n = len(A)\n dp = [0] * (n + 1)\n for j, (b, a) in enumerate(sorted(zip(B, A)), 1):\n for i in range(j, 0, -1):\n dp[i] = max(dp[i], dp[i - 1] + i * b + a)\n sa, sb = sum(A), sum(B)\n for i in range(0, n + 1):\n if sb * i + sa - dp[i] <= x:\n return i\n return -1\n```\n | 45 | 0 | ['C', 'Python', 'Java'] | 16 |
minimum-time-to-make-array-sum-at-most-x | Simple DP in C++, java & Python | simple-dp-in-c-java-python-by-cpcs-iwzx | Intuition\n\nSome conclusions:\n1. Each number will be cleared to 0 at most once. Since if we clear a number twice, we can skip the first time setting to make e | cpcs | NORMAL | 2023-08-05T16:49:30.135555+00:00 | 2023-08-05T16:58:01.472491+00:00 | 3,067 | false | # Intuition\n\nSome conclusions:\n1. Each number will be cleared to 0 at most once. Since if we clear a number twice, we can skip the first time setting to make everything earlier.\n2. The numbers with larger increasing rates (nums2[.]) should be cleared to 0 later than the numbers with smaller rates.\n\nSo if the numbers are sorted by the rates (nums2[.]), we need to select (at most) n numbers to clear in order.\n\nHowever, the difficulty is some numbers (with smaller rates) may not be selected when the sum matches the requriment.\n\n# Approach\nCreate a matrix with n rows and n columns. (To make it simpler, let indices start from 1 here).\nThe ith row and jth column is nums1[i] + nums2[i] * j, which is the value each number will be after j seconds. \n\nThe question changes into select j rows from the first j columns (one row per column), let the sum be s, we want sum(matrix[.][j]) - s <= x.\nHere sum(matrix[.][j]) is the sum of all the values in jth column which is a constant = nums1[0..n - 1] + nums2[0..n - 1] * j and x is also a constant. So our goal is to make s as large as possible.\n\nIn general to select one column in each row can be solved by graph matching, but this question\'s constraints are too large to a graph matching algorithm.\n\nWe can use dyanmaic programming.\n\ndp[i][j] means the maximum sum to select j columns from the first i rows (note j <= i).\ndp[i][j] = max(dp[i - 1][j], dp[i][j - 1] + nums1[i] + j * nums2[i])\nwhich is basically select the jth column or not.\n\n\n# Complexity\n- Time complexity:\nO(n ^ 2)\n\n- Space complexity:\nO(n) if we do some optimizations on DP.\n\n# Code\nC++\n```\nclass Solution {\npublic:\n int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n const int n = nums1.size();\n vector<int> ind(n);\n int s = 0, d = 0;\n for (int i = 0; i < n; ++i) {\n ind[i] = i;\n s += nums1[i];\n d += nums2[i];\n }\n if (s <= x) {\n return 0;\n }\n sort(ind.begin(), ind.end(), [&](const int a, const int b) {\n return nums2[a] < nums2[b];\n });\n vector<int> dp(n + 1);\n int r = n + 1;\n for (int i = 1; i <= n; ++i) {\n for (int j = min(i, r - 1); j; --j) {\n dp[j] = max(dp[j], dp[j - 1] + nums2[ind[i - 1]] * j + nums1[ind[i - 1]]);\n if (s + j * d - dp[j] <= x) {\n r = j;\n }\n }\n }\n return r <= n ? r : -1;\n }\n};\n```\n\nJava\n```\npublic class Solution {\n public int minimumTime(List<Integer> nums1, List<Integer> nums2, int x) {\n int n = nums1.size();\n Integer[] ind = new Integer[n]; // Using Integer array instead of int[]\n int s = 0, d = 0;\n for (int i = 0; i < n; ++i) {\n ind[i] = i;\n s += nums1.get(i);\n d += nums2.get(i);\n }\n if (s <= x) {\n return 0;\n }\n Arrays.sort(ind, (a, b) -> nums2.get(a) - nums2.get(b)); // Custom comparator\n int[] dp = new int[n + 1];\n int r = n + 1;\n for (int i = 1; i <= n; ++i) {\n for (int j = Math.min(i, r - 1); j > 0; --j) {\n dp[j] = Math.max(dp[j], dp[j - 1] + nums2.get(ind[i - 1]) * j + nums1.get(ind[i - 1]));\n if (s + j * d - dp[j] <= x) {\n r = j;\n }\n }\n }\n return r <= n ? r : -1;\n }\n}\n```\nPython:\n```\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n n = len(nums1)\n ind = list(range(n))\n s, d = 0, 0\n for i in range(n):\n s += nums1[i]\n d += nums2[i]\n if s <= x:\n return 0\n\n # Custom comparator for sorting ind based on nums2 values\n ind.sort(key=lambda i: nums2[i])\n\n dp = [0] * (n + 1)\n r = n + 1\n for i in range(1, n + 1):\n for j in range(min(i, r - 1), 0, -1):\n dp[j] = max(dp[j], dp[j - 1] + nums2[ind[i - 1]] * j + nums1[ind[i - 1]])\n if s + j * d - dp[j] <= x:\n r = j\n return r if r <= n else -1\n``` | 19 | 0 | ['Python', 'C++', 'Java', 'Python3'] | 6 |
minimum-time-to-make-array-sum-at-most-x | Video Explanation ("All" the proofs - Exchange Arguments) | video-explanation-all-the-proofs-exchang-f1xy | Explanation \n\nClick here for the video link\n\n# Code\n\n#define pii pair<int, int>\n#define F first\n#define S second\n\nint dp[1001][1001];\n\nclass Solutio | codingmohan | NORMAL | 2023-08-06T18:29:24.082636+00:00 | 2023-08-06T18:29:24.082654+00:00 | 491 | false | # Explanation \n\n[Click here for the video link](https://youtu.be/7KaJamPY7yA)\n\n# Code\n```\n#define pii pair<int, int>\n#define F first\n#define S second\n\nint dp[1001][1001];\n\nclass Solution {\n \n vector<int> n1, n2;\n \n int MaxSum(int row, int last_ind) {\n if (row == 0 || last_ind < 0) return 0;\n \n int& ans = dp[row][last_ind];\n if (ans != -1) return ans;\n \n ans = max (\n MaxSum (row, last_ind - 1),\n (n1[last_ind] + n2[last_ind]*row) + MaxSum (row-1, last_ind-1)\n );\n return ans;\n }\n \npublic:\n int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n int n = nums1.size();\n \n n1.clear(), n2.clear();\n n1.resize(n), n2.resize(n);\n \n vector<pii> n2_n1; \n for (int j = 0; j < n; j ++) n2_n1.push_back({nums2[j], nums1[j]});\n sort (n2_n1.begin(), n2_n1.end());\n \n for (int j = 0; j < n; j ++) {\n n1[j] = n2_n1[j].S;\n n2[j] = n2_n1[j].F;\n }\n \n memset(dp, -1, sizeof(dp));\n \n for (int op = 0; op <= n; op ++) {\n int sum = 0;\n for (int j = 0; j < n; j ++) sum += n1[j] + n2[j]*op;\n \n if ((sum - MaxSum(op, n-1)) <= x) return op;\n }\n \n return -1;\n }\n};\n``` | 14 | 0 | ['C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | C++ solution with explainations | c-solution-with-explainations-by-trantai-amxc | Intuition\nSome key observations: \n\nKey 1: The number of operations required should be no more than the length of the array. \n\nKey 2: There exist an optimiz | trantai | NORMAL | 2023-08-05T16:28:51.417090+00:00 | 2023-08-05T16:30:07.285013+00:00 | 1,104 | false | # Intuition\nSome key observations: \n\n**Key 1**: The number of operations required **should be no more than the length of the array**. \n\n**Key 2**: There exist an optimize way that **apply the operation to each indexes in the array atmost 1 time**. \n\n**Key 3**: Let\'s say for t operations, we are choosing to apply for t indexes: i1, i2, ..., it, the **one with higher nums2[] value will be apply later**. \n\nIndeed, let\'s say if nums2[i2] > nums2[i1] and operation applied for i1 at time t1, applied for i2 at time t2 where t1 > t2. Then if we applied the operation for i1 at t2, and for i2 at t1, we will have better result. (can write the difference between them to compare)\n\n\n# Approach\n\nWe will first sort the **pairs (nums2[i], nums1[i])** in increasing order of nums2[i]. \n\nWe will define a dp[time][n] as the maximum value we could deduced from the total sum (which is sigma(nums1[i]) + time * sigma(nums2[i])) if we apply the operations for **time** times consider the index up to n. \n\nThen the transition is: \n\n```\ndp[i][t] = max(dp[i-1][t], V[i-1].first * t + V[i-1].second + dp[i-1][t-1]);\n```\n\nif we don\'t includes the index i to the operations, \n```\n dp[i][t] = dp[i-1][t]\n``` \nif we includes the index i to the operations, as base on the key 1, the one with higher nums2[i] should have done later - which in this case, as times == t -> the remove is V[i-1].first **(this one is nums2[] value)** * t + V[i-1].second **(this one is nums1[] value)**\n```\n dp[i][t] = V[i-1].first * t + V[i-1].second + dp[i-1][t-1]\n``` \n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n^2)\n\n# Code\n```\nclass Solution {\npublic:\n int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n int n = nums1.size();\n int ss = accumulate(nums1.begin(),nums1.end(),0);\n int ss2 = accumulate(nums2.begin(),nums2.end(),0);\n if (ss <= x){\n return 0;\n }\n \n vector<pair<int, int>> V(n);\n for (int i = 0; i<n ;i++){\n V[i] = make_pair(nums2[i], nums1[i]);\n }\n \n sort(V.begin(), V.end());\n \n const int oo = 2e9;\n vector<vector<int>> dp(n + 1, vector<int>(n + 1));\n \n for (int t = 1; t <= n; t++){\n for (int i = 1; i <= n; i++){\n if (i < t){\n continue; \n }\n dp[i][t] = max(dp[i-1][t], V[i-1].first * t + V[i-1].second + dp[i-1][t-1]);\n }\n }\n \n //int ans = oo;\n for (int t = 1; t <= n; t++){\n int tot = ss2 * t + ss;\n //cout << tot << " " << dp[n][t] << "\\n";\n if (tot - dp[n][t] <= x){\n return t; \n }\n }\n return -1;\n }\n};\n``` | 14 | 0 | ['C++'] | 2 |
minimum-time-to-make-array-sum-at-most-x | Python solution | python-solution-by-leetcode_dafu-spe4 | observations: \n1. we will use at most n deletions\n2. each col will be deleted at most once. \n3. if one combination of deletions can make the sum less than x, | leetcode_dafu | NORMAL | 2023-08-05T16:08:16.218137+00:00 | 2023-08-05T19:11:30.323543+00:00 | 768 | false | observations: \n1. we will use at most n deletions\n2. each col will be deleted at most once. \n3. if one combination of deletions can make the sum less than x, then we can adjust the order of the deletions, so that those with larger nums2 are deleted later, which will create smaller total sum. \n\nSo, we sort nums2 from high to low and try all possible deletions with dp.\n\t \n\t \n\t nums=sorted(zip(nums1,nums2),key=lambda x: -x[1])\n n=len(nums)\n \n @lru_cache(2000) \n def t(i,j):\n if i==n or j==0: return 0\n return max(nums[i][0]+nums[i][1]*j+t(i+1,j-1), t(i+1,j)) \n \n t1=sum(nums1)\n t2=sum(nums2)\n for k in range(n+1):\n if t1+t2*k-t(0,k)<=x:\n return k \n return -1\n\n\n | 14 | 0 | [] | 1 |
minimum-time-to-make-array-sum-at-most-x | 🚀 Java O(n^2) DP with 💡 explanation and comments | java-on2-dp-with-explanation-and-comment-ihn5 | Intuition\nWe are going to use dynamic programming to build up an answer. We sort our pairs by nums2 values ascending, because zeroing out a nums1 value which h | mattihito | NORMAL | 2023-08-05T20:06:55.686977+00:00 | 2023-08-05T20:06:55.686998+00:00 | 276 | false | # Intuition\nWe are going to use dynamic programming to build up an answer. We sort our pairs by nums2 values ascending, because zeroing out a nums1 value which has a large nums2 value is best later (the earlier you do it, the more times you add nums2 value, and you don\'t want to do it twice, else why bother the first time).\n\nLet\'s talk about corresponding nums1 and nums2 values as "pairs". This just gives us an easier way to say it than thinking about two separate lists and corrresponding indices. In fact, we can transform the data into an array of pairs to make things easier to work with.\n\nThen we think about the fact that we can compute how much reduction we can do for 0 pairs (0 reduction in sum no matter how many operations), and we can compute how much reduction in sum we can get for i pairs and j operations as follows:\n- we cannot do worse than the reduction in sum we get from i - 1 pairs and j operations, because we are free to choose whether to zero out the i\'th pair or not with one of those j operations\n- but, we could do better if we look at the reduction from i - 1 pairs and j - 1 operations, then use an operation on the i\'th pair\n- so, we check both of these and take the maximum\n- this allows us to build up a two-dimensional `dp` array\n\nOnce we have the ability to know the max reduction for `j` operations on `i` pairs, we can find the minimum number of operations for which the sum reduction is sufficient for the total sum to be at most `x`.\n\n# Approach\nSo, to summarize, we are going to:\n- transform our data to pairs and sort them by their nums2 values ascending\n- create a `dp` array of size `[n + 1][n + 1]` to track the maximum sum reduction for using `j` operations among the first `i` pairs\n- now `dp[n][t]` is the optimal sum reduction in time `t`\n- without operations, the total sum at time `t` is `sum1 + (sum2 * t)`\n- so our answer is the smallest `t` such that `sum1 + (sum2 * t) - dp[n][t]` is less than or equal to `x` (or -1 if there is no such `t`)\n\n# Complexity\n- Time complexity: We have an O(n^2) buildup of the `dp` array.\n\n- Space complexity: Our `dp` array uses O(n^2) space\n\n# Java Code\n\nThis code ran in 18-20ms as of August, 2023 (faster than 100% at the time).\n\n```\nclass Solution {\n\n public int minimumTime(List<Integer> nums1, List<Integer> nums2, int x) {\n // We convert to array for faster int math and less clunky get(i)\n // syntax. This also gives us a single object pairs[i] to represent\n // each corresponding pair, and lets us sort our pairs easily.\n // While converting, we compute the sums of the two lists which we\n // will need later.\n final int[][] pairs = new int[nums1.size()][2];\n int sum1 = 0;\n int sum2 = 0;\n for (int i = 0; i < nums1.size(); ++i) {\n final int n1 = nums1.get(i);\n final int n2 = nums2.get(i);\n sum1 += n1;\n sum2 += n2;\n pairs[i][0] = n1;\n pairs[i][1] = n2;\n }\n // Sort pairs by nums2 value, breaking tie by nums1 value. Note\n // that the tiebreaker doesn\'t actually matter, but I prefer a\n // complete ordering (helps predictability if debugging, etc).\n Arrays.sort(pairs, (a, b) -> {\n int diff = Integer.compare(a[1], b[1]);\n if (diff == 0) {\n diff = Integer.compare(a[0], b[0]);\n }\n return diff;\n });\n final int n = pairs.length;\n // We are going to compute how much we reduce the total with j ops\n // using any combination of the first i elements, working up to\n // computing j ops using all n elements. Generally, we cannot do\n // worse by including elements with larger nums2 values for same\n // number of ops, since we are free to ignore these elements. So,\n // we start with the sum reduction for i - 1 values and j ops as a\n // baseline, then compare that baseline with what happens if we\n // remove one op and replace it with zeroing out the (i - 1)st\n // pair. This lends itself to dynamic programming. The value\n // dp[i][j] tracks the best sum reduction for j operations used\n // among the first i elements.\n final int[][] dp = new int[n + 1][n + 1];\n for (int i = 1; i <= n; ++i) {\n for (int j = 1; j <= i; ++j) {\n final int withoutIthPair = dp[i - 1][j]; // baseline\n final int withIthPair = dp[i - 1][j - 1] // one fewer op\n + (pairs[i - 1][1] * j) // reduce by j additions of num2\n + pairs[i - 1][0]; // reduce by initial num1\n dp[i][j] = Math.max(withoutIthPair, withIthPair);\n }\n }\n // Now, we just look for the fewest number of ops t which provides\n // sufficient sum-reduction to get the total sum at or below x.\n for (int t = 0; t <= n; ++t) {\n final int sum = sum1 + (sum2 * t) - dp[n][t];\n if (sum <= x) {\n return t;\n }\n }\n // And, we didn\'t find any such t, so the answer is -1.\n return -1;\n }\n\n}\n```\n\n# Standard Plea\nIf this posting was useful, helped you better understand the problem, or at least wasn\'t a waste of your time, **I would appreciate your upvote**. On the other hand, if you found it less than useful, **any constructive criticism in the comments is appreciated**. Thanks, and happy coding!\n | 11 | 0 | ['Array', 'Dynamic Programming', 'Java'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Optimized DP | optimized-dp-by-votrubac-vt10 | It was hard for me to see that this is a DP solution. \n\nI was not sure if previous computations can be reused. \n\nTurned out they can, but only if we process | votrubac | NORMAL | 2023-08-05T23:30:34.263449+00:00 | 2023-08-05T23:46:21.180067+00:00 | 1,020 | false | It was hard for me to see that this is a DP solution. \n\nI was not sure if previous computations can be reused. \n\nTurned out they can, but only if we process elements in the order of `n2`, increasing.\n\n**C++**\nBecause we only look one step back, we can optimize the memory to `dp[1001]`.\n\n```cpp\nint minimumTime(vector<int>& n1, vector<int>& n2, int x) {\n int sum1 = accumulate(begin(n1), end(n1), 0);\n int sum2 = accumulate(begin(n2), end(n2), 0);\n int dp[1001] = {}, n = n1.size();\n vector<int> ids(n1.size());\n iota(begin(ids), end(ids), 0); \n sort(begin(ids), end(ids), [&](int i, int j){ return n2[i] < n2[j]; });\n for (int i = 1; i <= n; ++i)\n for (int j = i; j > 0; --j)\n dp[j] = max(dp[j], dp[j - 1] + n2[ids[i - 1]] * j + n1[ids[i - 1]]);\n for (int t = 0; t <= n; ++t)\n if (sum1 + sum2 * t - dp[t] <= x)\n return t;\n return -1;\n}\n``` | 8 | 0 | ['C'] | 1 |
minimum-time-to-make-array-sum-at-most-x | N^2logN solution, DP + Binary search + Maths | n2logn-solution-dp-binary-search-maths-b-i6r5 | Intuition\nYou can see that after a certain day you can get the solution, which gives the intuition of binary search\n\n# Approach\nWe use binary search to get | yashsinghania | NORMAL | 2023-08-05T18:44:46.384520+00:00 | 2023-08-05T18:44:46.384547+00:00 | 672 | false | # Intuition\nYou can see that after a certain day you can get the solution, which gives the intuition of binary search\n\n# Approach\nWe use binary search to get the answer, the check funtion is a DP function. \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 int n;\n int dp[1003][1003];\n int f(vector<vector<int>> &v, int i, int &time, int t){\n if(i == n){\n return 0;\n }\n if(dp[i][t] != -1) return dp[i][t];\n if(t > time) return 0;\n int ans = max(f(v, i+1, time, t), f(v, i+1, time, t+1) + v[i][1] + t*v[i][0]);\n return dp[i][t] = ans;\n }\n \n int minimumTime(vector<int>& a, vector<int>& b, int x) {\n n = a.size();\n int ans = 0, suma = 0, sumb = 0;\n vector<vector<int>> v(n);\n for(int i = 0; i < n; i++){\n v[i] = {b[i], a[i]};\n suma += a[i];\n sumb += b[i];\n }\n sort(v.begin(), v.end());\n int total = 0;\n for(int i = 0; i < n; i++){\n int xx = n - i - 1;\n total += (xx * v[i][0]);\n }\n if(suma <= x) return 0;\n if(total > x) return -1;\n \n int lo = 0, hi = n, mid;\n while(lo <= hi){\n memset(dp, -1, sizeof(dp));\n mid = (lo + hi) / 2;\n int c = f(v, 0, mid, 1);\n int xx = suma + mid*sumb - c;\n // dbggg(mid, xx, c);\n if(xx <= x) hi = mid - 1;\n else lo = mid + 1;\n }\n return hi + 1;\n \n }\n};\n``` | 6 | 0 | ['C++'] | 7 |
minimum-time-to-make-array-sum-at-most-x | [C++] Intuitive explaination - math and sorting (not DP) | c-intuitive-explaination-math-and-sortin-oyqf | Intuition\nFirst we can see that selecting an index for the operation more than once is not helpful. If we choose index i for step S_k, then the value at that i | awesson | NORMAL | 2023-08-05T17:18:10.721917+00:00 | 2023-08-06T00:20:08.776858+00:00 | 465 | false | # Intuition\nFirst we can see that selecting an index for the operation more than once is not helpful. If we choose index $$i$$ for step $$S_k$$, then the value at that index for the sum at that step will be 0, regardless of whether we chose it at some earlier step. For this reason, we also know that it wont make sense to take more than N steps.\n\nLets call the sum of all numbers in nums1, $$SN1$$, and the sum all of numbers in nums2, $$SN2$$.\n\nWe can see that if we selected no index at each step, then after $$S$$ steps, the sum would be $$SN1 + S*SN2$$. We also see that selecting an index for an operation will remove $$n1_i$$ and $$S_k*n2_i$$ from that naive sum, where $$S_k$$ is the step when that index is selected.\n\nFor example, lets say $$nums1[i] = 4$$ and $$nums2[i] = 3$$. If we select this index for step 3 out of 5, then the base value of 4 and the first 3 additions of 3 will be zeroed out, leaving only 2 multiples of 3:\nstep 0: 4\nstep 1: 4 + 3 = 7\nstep 2: 7 + 3 = 10 \nstep 3: 10 + 3 = 13 => selected to be 0 \nstep 4: 13 + 3 = 16 ------------------- 0 + 3 = 3 \nstep 5: 16 + 3 = 19 ------------------- 3 + 3 = 6\nFor a difference of $$19 - 6 = n1 + S_k * n2 = 4 + 3*3 = 13$$.\n\nSince we wont chose the same index more than once, if we use the max N steps, each index will be chosen once, giving us a final sum of $$SN1 + N*SN2 - \\sum_{i=0}^N(n1_i + S_k*n2_i)$$. To get the lowest total sum possible, we should pick $$n2_i$$ values from lowest to highest (pairing larger n2 values with larger $$S_k$$ coefficents, increasing the sum being subtracted, which in turn decreases the overall sum).\n\nHowever, we might be able to get a sum below the given value in less steps. We can do so by working backwards and deciding which index to not select when going from using S steps to using S-1 steps instead. In this case where we use S instead of N steps, the sum is $$SN1 + S*SN2 - \\sum_{i=0}^S(n1_i + S_k*n2_i)$$. When we remove an index, we are removing $$n1_i + S_k*n2_i$$ from the subtraction *and* reducing the coeficents of all indices chosen after that index by 1 (based on the step they are selected in).\n\nFor example, lets say we have the best sum for when we choose 3 indices. Then this sum looks like $$SN1 + 3*SN2 - ((n1_0 + n2_0) + (n1_1 + 2*n2_1) + (n1_2 + 3*n2_2))$$ where we assume the indices are sorted by the value of n2, so that $$n2_2$$ is the largest (the value of n1 doesn\'t affect the ordering and therefore it doesn\'t affect the coefficent either, but it does affect which index to remove as you\'ll see shortly). If we remove index 2, then we remove only $$n1_2 + 3*n2_2$$ and the new sum is $$SN1 + 2*SN2 - ((n1_0 + n2_0) + (n1_1 + 2*n2_1))$$. But if we remove index 0, then we are removing $$n1_0 + n2_0$$ as well as one instance of $$n2_1$$ and one instance of $$n2_2$$, for a new sum of $$SN1 + 2*SN2 - ((n1_1 + n2_1) + (n1_2 + 2*n2_2))$$ (note the new coefficents which are one less than in the sum with three indicies).\n\nWe want this removed amount to be as small as possible to keep the subtraction as large as possible (keeping the sum as low as possible). So for each number of steps, we calculate this value for each remaining index and select the one with the smallest value to be removed.\n\n\n# Approach\nFirst calculate the sum of each array.\n\nSort the arrays by the value in nums2.\n\nCalculate the ideal sum when taking N steps by using this order.\n\nThen iteratively remove one selection which will increase the sum by the least amount, checking at each step if we are below the target sum.\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```\nclass Solution\n{\npublic:\n\tint minimumTime(vector<int>& nums1, vector<int>& nums2, int x)\n\t{\n\t\tint n = nums1.size();\n\t\tint minTime = -1;\n\n\t\tvector<pair<int, int>> pairedNums;\n\t\tint n1Sum = 0;\n\t\tint n2Sum = 0;\n\t\tfor (int i = 0; i < n; ++i)\n\t\t{\n\t\t\tpairedNums.push_back(make_pair(nums2[i], nums1[i]));\n\t\t\tn1Sum += nums1[i];\n\t\t\tn2Sum += nums2[i];\n\t\t}\n\t\tsort(pairedNums.begin(), pairedNums.end());\n\n\t\tif (n1Sum <= x)\n\t\t{\n\t\t\treturn 0;\n\t\t}\n\n\t\tfor (int i = 0; i < n; ++i)\n\t\t{\n\t\t\tvector<pair<int, int>> valueIfRemoved;\n\t\t\tint sum = n1Sum + (n - i) * n2Sum - selectedSum(pairedNums, valueIfRemoved);\n\t\t\tif (sum <= x)\n\t\t\t{\n\t\t\t\tminTime = n - i;\n\t\t\t}\n\n\t\t\tauto minRemovedValue = min_element(valueIfRemoved.begin(), valueIfRemoved.end());\n\t\t\tpairedNums.erase(pairedNums.begin() + minRemovedValue->second);\n\t\t}\n\n\t\treturn minTime;\n\t}\n\nprivate:\n\tint selectedSum(vector<pair<int, int>>& selected, vector<pair<int, int>>& valueIfRemoved)\n\t{\n\t\tint sum = 0;\n\t\tint n = selected.size();\n\t\tint sumPrevMultipliers = 0;\n\t\tfor (int i = n - 1; i >= 0; --i)\n\t\t{\n\t\t\tint value = (i + 1) * selected[i].first + selected[i].second;\n\t\t\tsum += value;\n\t\t\tvalueIfRemoved.push_back(make_pair(value + sumPrevMultipliers, i));\n\t\t\tsumPrevMultipliers += selected[i].first;\n\t\t}\n\t\treturn sum;\n\t}\n};\n``` | 6 | 0 | ['Math', 'Sorting', 'C++'] | 2 |
minimum-time-to-make-array-sum-at-most-x | (Memoization + Sorting ) Simple Algorithm 🔥🔥 | memoization-sorting-simple-algorithm-by-ic1pu | Code\n\nclass Solution {\nprivate:\n int n;\n long long sum1, sum2;\n vector<pair<int, int>> arr;\n\n // finds max sum which can be made in t time w | kingsman007 | NORMAL | 2023-09-08T05:50:27.008349+00:00 | 2023-09-08T05:50:27.008371+00:00 | 314 | false | # Code\n```\nclass Solution {\nprivate:\n int n;\n long long sum1, sum2;\n vector<pair<int, int>> arr;\n\n // finds max sum which can be made in t time with i as last index taken\n // using simple knapsack dp - take, not take\n\n long long dp[1001][1001];\n\n long long f(vector<int>& nums1 ,int t , int i) {\n // base case\n if(t == 0 or i < 0) return 0;\n // memoization case\n if(dp[t][i] != -1) return dp[t][i];\n // calling recursion\n long long notTake = f(nums1, t, i - 1);\n long long take = nums1[arr[i].second] + arr[i].first * 1ll * t\n + f(nums1, t - 1, i - 1);\n return dp[t][i] = max(take, notTake);\n }\n\npublic:\n int minimumTime(vector<int>& nums1 , vector<int>& nums2 , int x) {\n // using exchange arguments\n // Note:\n // 1. we can clear all elements at most once\n // 2. we need to clear elements in order of magnitude of nums2 elements\n\n n = nums1.size();\n sum1 = 0;\n sum2 = 0;\n arr = vector<pair<int, int>>();\n\n for(int i = 0 ; i < n ; i++) {\n arr.push_back({nums2[i] , i});\n sum1 += nums1[i];\n sum2 += nums2[i];\n }\n\n sort(arr.begin() , arr.end());\n memset(dp, -1, sizeof(dp));\n\n // using linear search\n // note: dp matrix will be filled atmost once thus tle is prevented\n\n for(int t = 0; t <= n; t++) {\n long long sum = sum1 + t * sum2;\n if(sum - f(nums1, t, n - 1) <= x) return t;\n }\n return -1;\n }\n};\n``` | 4 | 0 | ['Array', 'Dynamic Programming', 'Memoization', 'Sorting', 'C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Python solution (DP tab, explained) | python-solution-dp-tab-explained-by-olzh-eq4m | Approach\n Describe your approach to solving the problem. \nLet\'s consider the following example:\n- nums1 = [100, 5, 1, 1]\n- nums2 = [2, 1, 3, 5]\n\nSome obs | olzh06 | NORMAL | 2023-08-13T17:13:19.095657+00:00 | 2023-08-14T06:51:01.592684+00:00 | 203 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nLet\'s consider the following example:\n- `nums1 = [100, 5, 1, 1]`\n- `nums2 = [2, 1, 3, 5]`\n\nSome observations:\n1. At time `0` the result is `sum(nums1)` regardless of what the `nums2` elements are. If `sum(nums1) <= x`, the problem condition is satisfied at time `0`, so we just return `0`\n\n2. At time `t` the result can be represented by two parts:\n + the positive part which includes initial `sum(nums1)` plus increment, which is the same each second and equal to `sum(nums2)`. I.e., at time `t` the positive part is equal to `sum(nums1) + t * sum(nums2)`\n + the negative part due to performing the "reset" operation: setting the current value of element `j` (which at time `t` is equal to `nums1[j] + t * nums2[j]`) to `0`\n\n3. After applying the operation at selected index `j`, further value of this element does not depend on initial `nums1[j]` value and can be calculated as `nums2[j]` multiplied by time since the reset operation\n + this suggests that if we did not succeed after applying operation to each index (i.e., after `len(nums1)` seconds), the sum of array elements can not be mimimized to `<= x`\n\n4. From previous observation it is clear that if we need to reset several indices `j1 < j2 < j3 ...` it is reasonable to select them such that `nums2[j1] <= nums2[j2] <= nums2[j3] ...`. In this case the newly accumulated sum of `nums2[j] * time since reseting element at index j` for these indices will be minimal, that minimizes the overall result\n\n5. Item 4 suggests we have to sort `nums2` in non-decreasing order and rearrange `nums1` accordingly\n\n\nAfter sorting `nums2` and rearranging `nums1` we will get:\n- `nums1 = [5, 100, 1, 1]`\n- `nums2 = [1, 2, 3, 5]`\n\nIf we are given only 1 second, we will reduce the result by:\n- `5 + 1*1` if index `j = 0` is selected to perform operation;\n- `100 + 2*1` if index `j = 1` is selected, and so on.\n\nObviously, moving from smaller indeces to the larger ones we select the maximum value that can be reset from the value on the left and the one that can be obtained for current index. It looks like we can find our negative part of solution using dynamic programming.\n\nFor initial row we need a list of `0` of `len(nums1) + 1` size. I.e., for time `t = 0` and `t = 1` from the sample above we will get<br>\n`t=0: [0, 0, 0, 0, 0]`\n`t=1: [0, 6, 102, 102, 102]`\n\nThe result will be `sum(nums1) + sum(nums2) * t - dp[t=1][-1]` or `107 + 11 * 1 - 102 = 16`\n\nFor `t=2` since we agreed that it is reasonable to select indeces to reset in non-decreasing order of `nums2` we can write:<br>\n`dp[t][j+1] = max( dp[t][j], dp[t-1][j] + nums1[j] + t * nums2[j]) )` for `j in range(len(nums1))`\n\nThus we will get:<br>\n`t=2: [0, 7, 110, 110, 113]`, `result = 107 + 11 * 2 - 113 = 16`<br>\n`t=3: [0, 8, 113, 120, 126]`, `result = 107 + 11 * 3 - 126 = 14`<br>\n`t=4: [0, 9, 116, 126, 141]`, `result = 107 + 11 * 4 - 141 = 10`\n\nLet\'s check what happens if we continue:<br>\n`t=5: [0,10, 119, 132, 152]`, `result = 107 + 11 * 5 - 152 = 10`<br>\n`t=6: [0,11, 122, 138, 163]`, `result = 107 + 11 * 6 - 163 = 10`\n\nThat\'s exactly what was expected, we can not minimize the result any further\n# Complexity\n- Time complexity: O(n<sup>2</sup>), `n = len(nums1)`\n\n- Space complexity: O(n<sup>2</sup>) if we use dp matrix or O(n) if we use previous and current `dp` rows as in solution below\n\n# Code\n```python\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n # calculate sums for nums1, nums2\n sum1 = sum(nums1)\n if sum1 <= x:\n return 0\n sum2 = sum(nums2)\n n = len(nums1)\n \n # sort nums2 and rearrange nums1 accordingly\n nums2, nums1 = zip(*sorted(zip(nums2, nums1))) #type: ignore\n\n dp1 = [0]*(n+1)\n dp2 = [0]*(n+1)\n \n # use DP tabulation to calculate max value that can be reduced for first t seconds\n for t in range(1, n+1):\n for j in range(n):\n dp2[j+1] = max(dp2[j], dp1[j] + nums1[j] + nums2[j] * t)\n sum1 += sum2\n if sum1 - dp2[-1] <= x:\n return t\n dp1, dp2 = dp2, dp1\n return -1\n #end minimumTime(...)\n``` | 4 | 0 | ['Python3'] | 1 |
minimum-time-to-make-array-sum-at-most-x | C++ DP solution with explanation (~15lines) | c-dp-solution-with-explanation-15lines-b-5rei | Intuition\nAt time $t$, the sum of nums1 without any operations is $sum(nums1)+tsum(nums2)$ which is only dependent on $t$. So the problem turns to maximizing t | TonyCao7 | NORMAL | 2023-08-11T10:43:03.129007+00:00 | 2023-08-11T10:43:03.129037+00:00 | 85 | false | # Intuition\nAt time $t$, the sum of nums1 without any operations is $sum(nums1)+t*sum(nums2)$ which is only dependent on $t$. So the problem turns to maximizing the sum of elements we cleared with $t$ operations.\n## Intuition 1\n**Answer should be no larger than $n$.**\nIf the answer is larger than $n$, there must be at least one $i$ that has been cleared at least twice. In this case, the earlier operation is unecessary because it\'s covered by the latter one. \n## Intuition 2\n**index $i$ with smaller $nums2[i]$ should be cleared first.**\nSuppose we perform $t$ operations on index $i_1, i_2,... i_t$. The sum of elements we cleared will be $\\sum_{k=1}^t (nums1[i_k]+nums2[i_k]*k)$. \nFrom [rearrangement inequality](https://en.wikipedia.org/wiki/Rearrangement_inequality), $nums2[i_k]$ for $k =1...t$ should be accending.\nTherefore, to maximize the sum of elements cleared, we need to clear index $i$ with smaller $nums2[i]$ first.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nIt\'s like 0-1 knapsack dp.\ndp[i][j] is the maximum sum of elements cleared with the first $i+1$ elements and $j$ operations.\n$dp[i][j] = max(dp[i-1][j-1] + nums1[i-1] + j * nums2[i-1], dp[i-1][j])$ \nFinally, calculate the sum of elements from $t=0$ to $n$ to see if such $t$ exists.\n\n# Code\n```\nclass Solution {\npublic:\n int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n int s1 = accumulate(nums1.begin(), nums1.end(), 0), s2 = accumulate(nums2.begin(), nums2.end(), 0), n = nums1.size();\n vector<int> dp(n + 1, 0);\n vector<pair<int, int>> nums;\n\n for(int i = 0; i < n; i++)\n nums.push_back({nums2[i], nums1[i]});\n sort(nums.begin(), nums.end());\n\n for(int i = 0; i < n; i++)\n for(int j = i + 1; j > 0; j--)\n // clear the ith element or not\n dp[j] = max(dp[j], dp[j-1] + nums[i].second + j * nums[i].first);\n\n for(int t = 0; t <= n; t++)\n if(s1 + t * s2 - dp[t] <= x)\n return t;\n return -1;\n }\n};\n``` | 4 | 0 | ['C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | 💯✅ JAVA 8 STREAMS || EXPLAINED || 8 LINES || Intuition || Approach 🆙🆙⬆️⬆️ | java-8-streams-explained-8-lines-intuiti-jr38 | \n# Intuition: \n\nFor each task in nums1 and nums2, we can clear it at most once. If we clear a task twice, we are just wasting time by setting it to zero agai | ManojKumarPatnaik | NORMAL | 2023-08-05T16:42:04.628086+00:00 | 2023-08-05T17:26:44.719114+00:00 | 472 | false | \n# Intuition: \n\nFor each task in nums1 and nums2, we can clear it at most once. If we clear a task twice, we are just wasting time by setting it to zero again. Therefore, we should choose which tasks to clear carefully.\n\nTasks in the nums2 list with larger duration per operation should be cleared later than tasks with smaller duration per operation. That way, we can maximize the time we spend on the tasks with smaller duration per operation.\n\nIf we sort the tasks by their duration per operation, we can greedily choose the first k tasks to clear, where k <= n, and still meet the time requirement. However, some tasks with smaller duration per operation may not get chosen, even if clearing them does not cause us to exceed the time requirement.\n\n# Approach:\n\nWe create a 2D array nums of size n x 2, where each row i contains the pair (nums1[i], nums2[i]), which represent the time required for the ith task and the duration per operation of the ith task, respectively.\n\nWe sort the array nums in ascending order by the duration per operation. We use a two-dimensional dp array of size (n+1) x (n+1), where dp[i][j] represents the maximum total time we can spend by selecting j tasks from the first i tasks of nums, subject to the time constraint.\n\nWe fill the dp array using the following recurrence relation:\n\ndp[i][j] = max { dp[i-1][j], dp[i-1][j-1] + nums[i-1][0] + j * nums[i-1][1] }\n\nWe return the largest value of j for which dp[n][j] <= x.\n\n\n\n# Code:\n\n```JAVA []\npublic int minimumTime(List<Integer> nums1, List<Integer> nums2, int x) {\n\t\tint nums[][] = new int[nums1.size()][], sum1 = 0, sum2 = 0, dp[][] = new int[nums.length + 1][nums.length + 1];\n\t\tfor (int i = 0; i < nums1.size(); sum1 += nums1.get(i), sum2 += nums2.get(i), i++) {\n\t\t\tnums[i] = new int[] { nums1.get(i), nums2.get(i) };\n\t\t}\n\t\tArrays.sort(nums, (o, p) -> o[1] - p[1]);\n\t\tfor (int i = 0; i < nums1.size(); i++) {\n\t\t\tfor (int j = 1; j <= i + 1; j++) {\n\t\t\t\tdp[i + 1][j] = Math.max(dp[i][j], dp[i][j - 1] + nums[i][0] + j * nums[i][1]);\n\t\t\t}\n\t\t}\n\t\tfor (int i = 0; i <= nums2.size(); i++) {\n\t\t\tif (sum1 + sum2 * (long) i - dp[nums1.size()][i] <= x) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n```\n\n# using Java 8 streams\n```java [] \npublic int minimumTime(List<Integer> nums1, List<Integer> nums2, int x) {\n int size = nums1.size(),nums[][] = new int[size][],length = nums.length, dp[][] = new int[length + 1][length + 1];;\n AtomicInteger sum1 = new AtomicInteger(0),sum2 = new AtomicInteger(0),ans = new AtomicInteger(-1);\n IntStream.range(0,size).forEach(i->{\n nums[i] = new int[] { nums1.get(i), nums2.get(i) };\n sum1.addAndGet(nums1.get(i)); sum2.addAndGet(nums2.get(i));\n });\n Arrays.sort(nums, Comparator.comparingInt(o -> o[1]));\n IntStream.range(0,size).forEach(i->{\n IntStream.rangeClosed(1,i+1).forEach(j->{\n dp[i + 1][j] = Math.max(dp[i][j], dp[i][j - 1] + nums[i][0] + j * nums[i][1]);\n });\n });\n IntStream.range(0, nums2.size() + 1)\n .filter(i -> sum1.get() + sum2.get() * (long) i - dp[size][i] <= x)\n .findFirst()\n .ifPresent(ans::set);\n return ans.get();\n}\n```\n\uD83C\uDD99\u2B06\uFE0F\uD83C\uDD99\uD83C\uDD99\u2705\uD83D\uDCAF\n```\npublic int minimumTime(List<Integer> nums1, List<Integer> nums2, int x) {\n int size = nums1.size(),nums[][] = new int[size][],length = nums.length, dp[][] = new int[length + 1][length + 1];;\n AtomicInteger sum1 = new AtomicInteger(0),sum2 = new AtomicInteger(0);\n IntStream.range(0,size).forEach(i->{\n nums[i] = new int[] { nums1.get(i), nums2.get(i) };\n sum1.addAndGet(nums1.get(i)); sum2.addAndGet(nums2.get(i));\n });\n Arrays.sort(nums, Comparator.comparingInt(o -> o[1]));\n IntStream.range(0,size).forEach(i->IntStream.rangeClosed(1,i+1).forEach(j->dp[i + 1][j] = Math.max(dp[i][j], dp[i][j - 1] + nums[i][0] + j * nums[i][1])));\n return IntStream.range(0, nums2.size() + 1).filter(i -> sum1.get() + sum2.get() * (long) i - dp[size][i] <= x).findFirst().orElse(-1); \n}\n```\nC++:\n\n```\nint minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n int n = nums1.size();\n vector<vector<int>> nums(n, vector<int>(2));\n for (int i = 0; i < n; i++) {\n nums[i][0] = nums1[i];\n nums[i][1] = nums2[i];\n }\n sort(nums.begin(), nums.end(), [](auto& a, auto& b) { return a[1] < b[1]; });\n vector<vector<int>> dp(n+1, vector<int>(n+1));\n for (int i = 1; i <= n; i++) {\n for (int j = 1; j <= i && j <= n; j++) {\n dp[i][j] = max(dp[i-1][j], dp[i-1][j-1] + nums[i-1][0] + j * nums[i-1][1]);\n }\n }\n for (int j = n; j >= 0; j--) {\n if (dp[n][j] <= x) {\n return j;\n }\n }\n return -1;\n}\n```\n\nPython:\n\n```\ndef minimumTime(nums1: List[int], nums2: List[int], x: int) -> int:\n n = len(nums1)\n nums = [[nums1[i], nums2[i]] for i in range(n)]\n nums.sort(key=lambda a: a[1])\n dp = [[0]*(n+1) for _ in range(n+1)]\n for i in range(1, n+1):\n for j in range(1, i+1):\n dp[i][j] = max(dp[i-1][j], dp[i-1][j-1] + nums[i-1][0] + j * nums[i-1][1])\n for j in range(n, -1, -1):\n if dp[n][j] <= x:\n return j\n return -1\n```\n\n# Complexity\n- Time complexity:o(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> | 4 | 1 | ['Dynamic Programming', 'Data Stream', 'Python', 'C++', 'Java', 'Python3'] | 2 |
minimum-time-to-make-array-sum-at-most-x | 💥💥 Beats 100% on runtime and memory [EXPLAINED] | beats-100-on-runtime-and-memory-explaine-w7gx | IntuitionFigure out how to spend time in a way that minimizes a result, considering both time and starting values, while trying to find an optimal selection of | r9n | NORMAL | 2025-01-07T05:03:39.841116+00:00 | 2025-01-07T05:03:39.841116+00:00 | 18 | false | # Intuition
Figure out how to spend time in a way that minimizes a result, considering both time and starting values, while trying to find an optimal selection of elements from two lists. I realized that sorting the pairs and using recursion with memoization would help efficiently explore the possible options without recalculating overlapping subproblems.
# Approach
Sort the pairs in descending order based on one list, then use recursion with memoization (stored in a HashMap) to calculate the best result for each possible time, considering whether to take or skip each pair.
# Complexity
- Time complexity:
O(n^2) because of the recursive DFS combined with sorting the array, where n is the length of the lists.
- Space complexity:
O(n^2) as well, due to the memoization storage (HashMap), where n is the number of elements in the input lists.
# Code
```rust []
use std::collections::HashMap;
impl Solution {
pub fn minimum_time(nums1: Vec<i32>, nums2: Vec<i32>, x: i32) -> i32 {
let n = nums1.len() as i32; // Convert the length to i32
let mut nums: Vec<(i32, i32)> = nums1.iter()
.zip(nums2.iter())
.map(|(&n1, &n2)| (n2, n1))
.collect();
nums.sort_by(|a, b| b.cmp(a)); // Sort in reverse order
// Memoization storage using HashMap
let mut cache: HashMap<(i32, i32), i32> = HashMap::new(); // Change usize to i32 in the cache key
// DFS function with memoization
fn dfs(nums: &[(i32, i32)], i: i32, time: i32, cache: &mut HashMap<(i32, i32), i32>) -> i32 {
if time == 0 {
return 0;
}
if i == nums.len() as i32 {
return 0;
}
// Check the cache
if let Some(&result) = cache.get(&(i, time)) {
return result;
}
let (speed, start) = nums[i as usize];
let mut local_res = start + speed * time + dfs(nums, i + 1, time - 1, cache);
// Skip this number, only if there are enough elements left for time
if nums.len() as i32 - i > time {
local_res = local_res.max(dfs(nums, i + 1, time, cache));
}
// Store the result in the cache
cache.insert((i, time), local_res);
local_res
}
let sum1: i32 = nums1.iter().sum();
let sum2: i32 = nums2.iter().sum();
for time in 0..=n {
let result = sum1 + time * sum2 - dfs(&nums, 0, time, &mut cache);
if result <= x {
return time;
}
}
-1
}
}
``` | 3 | 0 | ['Array', 'Math', 'Binary Search', 'Dynamic Programming', 'Recursion', 'Memoization', 'Sorting', 'Data Stream', 'Rust'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Recursive Solution O(n^2) beats nobody | recursive-solution-on2-beats-nobody-by-s-6eaa | This isn\'t an optimal solution (in particular it isn\'t space-optimal) but I think it will be helpful.\n\n# Intuition\nWe have n counters; counter i has an ini | space_dancer | NORMAL | 2023-08-17T02:52:17.895235+00:00 | 2023-08-17T02:52:17.895256+00:00 | 194 | false | This isn\'t an optimal solution (in particular it isn\'t space-optimal) but I think it will be helpful.\n\n# Intuition\nWe have `n` counters; counter `i` has an initial value `nums1[i]` and increases at a rate of `nums2[i]`.\n\nNote first that it is suboptimal to reset a counter (to zero) more than once, since then the first reset is wasted. Therefore, we should consider up to `n` steps at most; if we can\'t get the sum of the counters to be `x` or lower, then we will never be able to. However, it is sometimes possible to finish in `k < n` steps. \n\nWe can also reformulate the problem as a matter of achieving maximum reduction. The total sum increases by $\\sum rate_i$ with every timestep, and whenever we reset a counter $i$ at time $t_i$ we reduce the total sum by $initial_i + t_i * rate_i$. This also means if that we decide which counters we are going to reset, the optimal order is to reset the counters in increasing order of rate. That way, when $t_i$ is higher we get a greater reduction with higher $rate_i$.\n\nThe harder part is figuring out which counters we are going to reset in the first place if we are trying to finish in less than $n$ steps.\n\n# Approach\nWe try to find a recurrence which would be useful for calculating maximum reduction. Trying to calculate $M(t)$, the maximum reduction after $t$ steps, by itself, seems implausible since it\'s not obvious how $M(t)$ relates to $M(t-1)$ (or $M(t+1)$). Instead, consider the following: we try to calculate $M(t, s)$, the maximum reducton after $t$ steps and using the $s$ counters with lowest rates.\n\nThis is a bit of a leap: why the $s$ counters with lowest rates? I don\'t have a way of suggesting how you should think of this in the first place, but it\'s easy to explain afterwards: in the end we don\'t care about any value of $s$ other than $n$ anyway, and using the $s$ counters with the lowest rates makes the recurrence easy.\n\nWhen calculating $M(t, s)$, we consider two cases: either we reset the $s$th counter (1-indexed) or we didn\'t.\n* If we reset the $s$th counter, the optimal order includes resetting it at time $t$, so we can refer to $M(t-1, s-1)$ to calculate the reduction.\n* If we didn\'t reset the $s$th counter (which is only a case when $t > s$), then the reduction is the same as $M(t, s-1)$.\n\nOnce we\'ve calculated all relevant values of $M(t,s)$ we can simply look at the values of $M(t, n)$ for all $t \\in [0, n]$; if we attain enough of a reduction to get below the threshold $x$, then we are done.\n\n# Complexity\n- Time complexity: $O(n^2)$\n- Space complexity: $O(n^2)$ due to the number of cases in cache\n\nIt is possible to reduce the space usage to $O(n)$ with a bottom-up approach; $M(t,s)$ only relies on $M(t-1, s-1)$ and $M(t, s-1)$, prior values of $s$ do not need to be kept around in memory forever. Other solutions do this.\n\n# Code\n```\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n total_initial = sum(nums1)\n total_rate = sum(nums2)\n n = len(nums1)\n counters = sorted(zip(nums2, nums1)) # (rate, initial); sorted in increasing order of rate\n \n # Require that counters_end_idx >= t\n @lru_cache(None)\n def calc_max_reduction(counters_end_idx: int, t: int) -> int:\n if t == 0:\n return 0\n \n # Get the last counter (with highest rate)\n rate, initial = counters[counters_end_idx - 1]\n\n # This is the case where we reduce this counter at time t\n res = calc_max_reduction(counters_end_idx - 1, t - 1) + rate * t + initial\n \n # This is the case where we don\'t reduce this counter at time t\n # (Not available if items_end == n_steps since we would be forced to reduce the counter)\n if counters_end_idx > t:\n res = max(res, calc_max_reduction(counters_end_idx - 1, t))\n\n return res\n\n for t in range(0, n + 1):\n max_reduction = calc_max_reduction(n, t)\n if total_initial + t * total_rate - max_reduction <= x:\n return t\n\n return -1\n``` | 2 | 0 | ['Python3'] | 1 |
minimum-time-to-make-array-sum-at-most-x | Detailed and well explained C++ Solution ✔️✔️✔️ | detailed-and-well-explained-c-solution-b-qx46 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1. Create a 2D vector v of size n by 2, where v[i][0] stores the value of | __AKASH_SINGH___ | NORMAL | 2023-08-05T19:47:10.000461+00:00 | 2023-08-05T19:47:10.000481+00:00 | 244 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Create a 2D vector v of size n by 2, where v[i][0] stores the value of nums2[i] and v[i][1] stores the value of nums1[i].\n\n2. Sort the 2D vector v based on the values in nums2 in non-decreasing order. Sorting helps in selecting the optimal elements for the operations.\n\n3. Initialize a vector dp of size n+1 to keep track of the maximum values that can be obtained for each position in nums2 by considering operations involving elements from both nums1 and nums2.\n\n4. The first loop iterates from j = 1 to j = n. Within this loop, there is another loop that iterates over i in reverse order, starting from i = j and going down to i = 1.\n\n5. In the nested loop, calculate the maximum value that can be obtained for the operation at position j considering i elements from nums2 and elements from nums1. Update dp[i] with the maximum of two values:\n\n6. The current value of dp[i].\nThe sum of dp[i-1] + i * v[j-1][0] + v[j-1][1], representing the maximum value we can save by selecting i elements from nums2 and performing the operation with elements at positions i and j.\nAfter the first loop, the dp vector will contain the maximum values that can be obtained for each position in nums2 by considering operations involving elements from both nums1 and nums2.\n\n7. Calculate the sum of all elements in nums1 and store it in the integer variable suma. Calculate the sum of all elements in nums2 and store it in the integer variable sumb.\n\n8. The second loop iterates from i = 0 to i = n. Within this loop, check if the condition sumb * i + suma - dp[i] <= x is satisfied.\n\n9. If the condition is satisfied, it means that selecting i elements from nums2 and performing operations with elements from both nums1 and nums2 will not exceed the constraint x. In this case, the function returns the value of i, which represents the minimum time needed to meet the constraint.\n\n10. If the condition is not satisfied for any value of i within the loop, it means that there is no valid combination of elements that satisfies the constraint x. In this case, the function returns -1 to indicate that the constraint cannot be met.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n int n = size(nums1);\n vector<int> dp(n+1);\n vector<vector<int>> v(n, vector<int>(2));\n for(int i = 0; i<n; ++i) v[i][0] = nums2[i], v[i][1] = nums1[i];\n sort(v.begin(), v.end());\n for(int j = 1; j<=n; ++j)\n for(int i = j; i>=1; --i) dp[i] = max(dp[i], dp[i-1] + i*v[j-1][0] + v[j-1][1]);\n int suma = accumulate(nums1.begin(), nums1.end(), 0);\n int sumb = accumulate(nums2.begin(), nums2.end(), 0);\n for(int i = 0; i<=n; ++i)\n if(sumb*i + suma - dp[i] <= x) return i;\n return -1;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | [C++] simple dp | c-simple-dp-by-cuny-66brother-2k0k | \nusing ll = long long;\n\nconst int N = 1010, INF = 1e9;\nll dp[N][N];\n\nvoid init(int n) {\n for(int i = 0; i <= n; i++) {\n for(int j = 0; j <= n; | CUNY-66brother | NORMAL | 2023-10-10T15:48:33.679438+00:00 | 2023-10-10T15:48:33.679466+00:00 | 10 | false | ```\nusing ll = long long;\n\nconst int N = 1010, INF = 1e9;\nll dp[N][N];\n\nvoid init(int n) {\n for(int i = 0; i <= n; i++) {\n for(int j = 0; j <= n; j++) {\n dp[i][j] = -INF;\n }\n }\n}\n\nclass Solution {\npublic:\n int minimumTime(vector<int>& a, vector<int>& b, int x) {\n int n = a.size();\n init(n);\n long long s1 = 0, s2 = 0;\n for(int x : a) s1 += x;\n for(int x : b) s2 += x;\n \n if(s1 <= x) return 0; \n \n vector<ll> p(n + 1);\n for(int i = 1; i <= n; i++) {\n p[i] = s1 + s2 * i;\n }\n \n vector<pair<int, int>> c;\n for(int i = 0; i < n; i++) c.push_back({b[i], a[i]});\n sort(c.begin(), c.end());\n \n //base not change\n //select x integers\n dp[0][0] = 0;\n for(int i = 1; i <= n; i++) {\n int x = c[i - 1].second, y = c[i - 1].first;\n for(int j = 0; j <= i; j++) {\n dp[i][j] = dp[i - 1][j];\n if(j) {\n dp[i][j] = max(dp[i][j], dp[i - 1][j - 1] + x + (j + 0ll) * y);\n }\n }\n }\n \n for(int j = 1; j <= n; j++) {\n for(int i = 1; i <= n; i++) {\n if(dp[i][j] + x >= p[j]) {\n return j;\n }\n }\n }\n \n return -1;\n }\n};\n``` | 1 | 0 | [] | 0 |
minimum-time-to-make-array-sum-at-most-x | Taking same number a second time is same as taking it only one time | taking-same-number-a-second-time-is-same-r3zx | Intuition\nKey Observations:\n1. If you take nums[i] both at time 2 and at time 5, the result is same as taking nums[i] only at time 5. And taking only at time | yuanzhi247012 | NORMAL | 2023-08-15T06:41:53.759324+00:00 | 2023-08-18T07:02:01.519038+00:00 | 253 | false | # Intuition\nKey Observations:\n1. If you take nums[i] both at time 2 and at time 5, the result is same as taking nums[i] **only** at time 5. And taking **only** at time 5 is better because you save one extra round. \nBecause of this, it make no sense to take any index a second time. Each index can only be taken once. We only need to consider n number of time.\n2. If time is decided, mimimum remaining sum can be calculated using maximum sum taken away.\n3. If both time and indexes to take are decided, we can easily find out the max sum that can be taken away. Just sum all nums1 in given indexes, and sort nums2 in the given indexes from big to small.\n3. Now we need to list all combinations of indexes at given time, and find out which combination offers the biggest sum that can be taken away.\nCombination problem can typically be optimized by DP, by scanning each index and decide to "take-or-not-take" it.\n\n# Complexity\nTime: O(n^2)\nSpace: O(n)\nThe top-down recursive memorization appraoch is straightforward, but will exceed **memory** limit for its O(n^2) memroy. To pass we have to translate the recursive way to iterative way so as to save one extra demension of memory.\nThis is probably the first question in leetcode that set stricker memory limit than time limit. \n\n\n# Code\nRecursive approach (memory limit exceeded):\n``` python\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n n = len(nums1)\n A = sorted(zip(nums2,nums1),reverse=True)\n @cache\n def dp(i,time):\n if i>=n or not time: \n return 0\n take = A[i][0]*time+A[i][1] + dp(i+1,time-1)\n noTake = dp(i+1,time)\n return max(take,noTake)\n sm1,sm2 = sum(nums1),sum(nums2)\n for time in range(n+1):\n if (sm2*time + sm1 - dp(0,time)) <= x:\n return time\n return -1\n```\n\nIterative approach translated from recursive (Pass):\n``` python\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n n = len(nums1)\n sm1,sm2 = sum(nums1),sum(nums2)\n if sm1<=x:\n return 0\n A = sorted(zip(nums2,nums1))\n dp = [0]*(n+1)\n for time in range(1,n+1):\n dp2 = [0]*(n+1)\n for i in range(n):\n take = A[i][0]*time+A[i][1]+dp[i-1]\n noTake = dp2[i-1]\n dp2[i] = max(take,noTake)\n dp = dp2\n if (sm2*time+sm1-dp[n-1]) <= x:\n return time\n return -1\n``` | 1 | 0 | ['Python3'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Straightforward cpp solution :) | straightforward-cpp-solution-by-sanyam46-jjsa | 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 | sanyam46 | NORMAL | 2023-08-09T13:51:38.641376+00:00 | 2023-08-09T13:51:38.641419+00:00 | 134 | 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 int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) \n {\n int n = nums1.size();\n vector<int> indices(n);\n int s = 0;\n int d = 0;\n for(int i=0; i<n; i++)\n {\n indices[i] = i;\n s += nums1[i];\n d += nums2[i];\n }\n if(s<=x)\n {\n return 0;\n }\n sort(indices.begin() , indices.end() , [&](const int a , const int b)\n {\n return nums2[a]<nums2[b];\n });\n vector<int> dp(n+1);\n int r = n+1;\n for(int i=1; i<=n; i++)\n {\n for(int j=i; j>0; j--)\n {\n dp[j] = max(dp[j] , dp[j-1]+nums2[indices[i-1]]*j + nums1[indices[i-1]]);\n }\n }\n for(int t=0; t<=n; t++)\n {\n if(s + d*t - dp[t] <=x)\n {\n return t;\n }\n }\n return -1;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Vanilla dynamic programming to understand the logic | vanilla-dynamic-programming-to-understan-aica | This post is inspired by https://leetcode.com/problems/minimum-time-to-make-array-sum-at-most-x/solutions/3868304/simple-dp-in-c-java-python/ !\n# Intuition\n D | superPandaPlus | NORMAL | 2023-08-06T20:59:41.511018+00:00 | 2023-08-06T21:01:35.406371+00:00 | 252 | false | This post is inspired by https://leetcode.com/problems/minimum-time-to-make-array-sum-at-most-x/solutions/3868304/simple-dp-in-c-java-python/ !\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt is important to realize that the problem can be translated as: given j steps, and i rows (nums and their corresponding increaments), what is the largest sum we can get. This largest sum is the value that will be subtracted from the total.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nUse dynamic programming. Credit to the [post](https://leetcode.com/problems/minimum-time-to-make-array-sum-at-most-x/solutions/3868304/simple-dp-in-c-java-python/) referenced before. Here I use the vanilla dp approach for an easy understanding. To make it clear:\n\n1. outerloop for step numbers. For any given step numbers allowed, loop over numbers of rows we can choose. This is not necessary but will make the logic more clear.\n2. It is a bit tricky to understand why we need to sort the candidates (the numbers to delete) by their corresponding increaments. \n * A way to think of it is, because you want to delete as much as you can. so given j steps, when it comes to delete the jth number (consider it as the last number you have), you want to delete it such that it has the possible largest accumulation. Therefore you have to sort the increments from small to last, in order to meet this criterion for every given J loop.\n * (**Note:** indeed for a given J, you may have more candidates to choose, so deleting the jth number may not necessary give you the final answer; don\'t forget the number itself plays a role too, not just the increments. This is why in the dp, you see the maximum selection. But when j == n, you have no choice but to delete all the numbers, which means all the numbers are selected). \n\nTry print the dp matrix and you will see why.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n\n# Code\n```\nclass Solution {\n public int minimumTime(List<Integer> nums1, List<Integer> nums2, int x) {\n /*\n * dp definition \n * dp[i][j]: given (i + 1) numbers, we can delete j times, then what is the\n * maximum we are able to delete\n */\n \n int n = nums1.size();\n int[][] dp = new int[n + 1][n + 1];\n \n Integer[] idxSortedByVal = new Integer[n];\n\n // calculate the base\n int base = 0;\n int increase = 0;\n for (int i = 0; i < n; i++) {\n idxSortedByVal[i] = i;\n\n base += nums1.get(i);\n increase += nums2.get(i);\n }\n\n if (base <= x) {\n return 0;\n }\n\n // sort is must, to ensure we delete the maximum increament\n // at jth step, it is always best to delete a number with largest increament in the last step.\n Arrays.sort(idxSortedByVal, (a, b) -> nums2.get(a) - nums2.get(b)); \n\n for (int j = 1; j <= n; j++) {\n for (int i = j; i <= n; i++) {\n // how to get dp[i][j]:\n // 1. we do nothing, use dp[i - 1][j]\n // 2. we use this nums[i - 1]\n // we have to compare and choose the max. \n // This is because besides the increaments, the number also contributes to the dp[i][j], and they can "compete"\n dp[i][j] = Math.max(dp[i - 1][j], \n dp[i - 1][j - 1] \n + nums1.get(idxSortedByVal[i - 1]) + j * nums2.get(idxSortedByVal[i - 1]));\n\n int total = base + increase * j;\n\n // System.out.printf("j: %d | i: %d | total: %d | dp[i][j]: %d%n", \n // j, i, total, dp[i][j]);\n\n if (total - dp[i][j] <= x) {\n // meet the condition\n // System.out.printf("meet condition!");\n\n return j;\n }\n }\n }\n\n // impossible\n return -1;\n\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Intuition, approaching, proof and code | intuition-approaching-proof-and-code-by-gidjg | Intuition\n\nEDITED: fix some error, add the proof of max_possible_ops.\nEDITED 2: fix error in proof of max_possible_ops\n\n## Notations\n\nLet $A$ be the orig | 6cdh | NORMAL | 2023-08-06T10:57:47.622724+00:00 | 2023-08-08T01:18:18.596658+00:00 | 288 | false | # Intuition\n\nEDITED: fix some error, add the proof of `max_possible_ops`.\nEDITED 2: fix error in proof of `max_possible_ops`\n\n## Notations\n\nLet $A$ be the original `nums1`, $B$ be the original `nums2`.\nSo $A_i$ is `nums1[i]`.\nLet the length of `nums1` be $n$.\n\n## Limit\n\nAfter $n$ seconds, a intuition is that the minimum possible sum we can get of `nums1` will not decrease. So we only consider the time $[0,n]$. The proof is at the end of the Approach section.\n\n## After k seconds\n\nAfter $k$ seconds, if we don\'t do operations, `nums1` will become this:\n\n$$\nA_0 + k \\times B_0, A_1 + k \\times B_1, ..., A_{n-1} + k \\times B_{n-1}\n$$\n\nThen we add $k$ operations now, it equivalents we pick $k$ indexes $i_0, ..., i_{k-1}$, and change the values at these indexes are\n\n$$\n0, B_{i_1}, 2B_{i_2}, 3B_{i_3}, ..., (k-1)B_{i_{k-1}}\n$$\n\nNote we can pick indexes less than $k$, that means we reset twice for a index `j`. But then we can choose the earlier reset of `j`, and replace it with the reset of another index to make the sum of `nums1` smaller. That means a $k$ indexes solution is always better.\n\nThe sum of the current `nums1` is\n\n$$\n\\sum A + k \\sum B - (kB_{i_0} + (k-1)B_{i_1} + \\cdots + B_{i_{k-1}} + A_{i_0} + A_{i_1} + \\cdots + A_{i_{k-1}})\n$$\n\nTo make this minimize, it means to make this maximize\n\n$$\nkB_{i_0} + (k-1)B_{i_1} + \\cdots + B_{i_{k-1}} + A_{i_0} + A_{i_1} + \\cdots + A_{i_{k-1}}\n$$\n\n## Conclusion\n\nIn other words, we pick $k$ elements $b_0, b_1, ..., b_{k-1}$ from $B$ and their corresponding elements in $A$: $a_0,a_1, ..., a_{k-1}$, and try to maximize this:\n\n$$\nkb_0 + a_0 + (k-1)b_1 + a_1 + \\cdots + b_{k-1} + a_{k-1}\n$$\n\n# Approach\n\nIt\'s easy. For example, if we already chosen $k$ indexes, then sort all chosen $b_i$ in decreasing order, and calculate the formula in order to maximize it.\n\nSo it means we can just sort `nums2` and run dynamic programming on it. The complexity is $O(nk)$. The cached function looks like this:\n\n```python\nminimum_sum(i, k)\n```\n\nwhere `i` is the index, `k` is the number of operations.\n\nThen we scan from `0` to `max_possible_ops`:\n\n```python\nfor k in range(0, max_possible_ops):\n if minimum_sum(0, k) <= x:\n return k\nreturn -1\n```\n\nWhat is `max_possible_ops`?\n\nAfter $n$ seconds, every element is reset at least once. We only consider their latest reset.\n\nSuppose after $t+1$ seconds, we have sequence $a$ that can maximize this formula:\n\n$$\na_0B_0 + a_1B_1 + \\cdots + a_{n-1}B_{n-1} + \\sum A\n$$\n\n$1 \\le a_i \\le t+1$\n\nThe same for $t$ seconds, we have sequence $b$\n\n$$\nb_0B_0 + b_1B_1 + \\cdots + b_{n-1}B_{n-1} + \\sum A\n$$\n\n$1 \\le b_i \\le t$\n\nBoth sequence have no duplicate. $a$ contains $t+1$, $b$ contains $t$ for the latest reset. And $t \\ge n$.\n\nThen the increment will be\n\n$$\n\\sum B - (a_0B_0 + a_1B_1 + \\cdots + a_{n-1}B_{n-1})\n+ (b_0B_0 + b_1B_1 + \\cdots + b_{n-1}B_{n-1})\n$$\n\nThe two expression in the parentheses were maximized. We can simply sort $B$ in decreasing order and make sequence $a$ be $t+1, t, ..., t-n+2$, and $b$ be $t, t-1, ..., t-n+1$ to achieve this.\n\nFinally,\n\n$$\n\\sum B - (a_0B_0 + a_1B_1 + \\cdots + a_{n-1}B_{n-1})\n+ (b_0B_0 + b_1B_1 + \\cdots + b_{n-1}B_{n-1})\\\\\n= 0\n$$\n\nThat means the minimum sum of `nums1` after time $n$ will not decrease, and will not change actually. So `max_possible_ops` can be $n+1$.\n\n# Complexity\n\n- Time complexity: $O(n^2)$\n- Space complexity: $O(n^2)$\n\n# Code\n\nRacket code\n\n```racket\n(define (minimum-time nums1 nums2 x)\n (define inf #e1e10)\n (define sum1 (list-sum nums1))\n (define sum2 (list-sum nums2))\n (vec! nums1 nums2)\n (define n (alen nums1))\n (define sorted2\n (list->vector\n (sort (range 0 n)\n (\u03BB (a b)\n (> (aref nums2 a) (aref nums2 b))))))\n\n (define (indexof i)\n (aref sorted2 i))\n\n (define (minimum-sum i op)\n (match i\n [(== n) (if (= op 0) sum1 inf)]\n [i (min (minimum-sum (add1 i) op)\n (if (= op 0)\n inf\n (+ sum2\n (- (aref nums1 (indexof i)))\n (- (* op (aref nums2 (indexof i))))\n (minimum-sum (add1 i) (sub1 op)))))]))\n\n (cachef! minimum-sum n (add1 n) -1)\n\n (or (for/first ([op (in-closed-range 0 n)]\n #:when (<= (minimum-sum 0 op) x))\n op)\n -1))\n\n\n(require syntax/parse/define)\n\n(define-syntax make-array\n (syntax-rules ()\n [(_ n init)\n (make-vector n init)]\n [(_ n args ...)\n (build-vector n (lambda _ (make-array args ...)))]))\n\n(define-syntax aref\n (syntax-rules ()\n [(_ arr) arr]\n [(_ arr i args ...)\n (aref (vector-ref arr i) args ...)]))\n\n(define-syntax aset!\n (syntax-rules ()\n [(_ arr i v)\n (vector-set! arr i v)]\n [(_ arr i args ... v)\n (aset! (vector-ref arr i) args ... v)]))\n\n(define-syntax-rule (alen arr)\n (vector-length arr))\n\n(define-syntax-parse-rule (cachef! fn:id args:expr ...)\n (set! fn (cachef fn args ...)))\n\n(define-syntax-parser cachef\n [(_ fn:id)\n #\'(cachef-hash fn)]\n [(_ fn:id hints:expr ... init)\n (with-syntax ([(args ...) (generate-temporaries #\'(hints ...))])\n #\'(let* ([cache (make-array hints ... init)]\n [ori-fn fn])\n (lambda (args ...)\n (cond [(or (< args 0) ...\n (>= args hints) ...)\n (ori-fn args ...)]\n [else\n (when (equal? init (aref cache args ...))\n (aset! cache args ... (ori-fn args ...)))\n (aref cache args ...)]))))])\n\n(define (cachef-hash fn)\n (let ([cache (make-hash)])\n (lambda args\n (when (not (hash-has-key? cache args))\n (hash-set! cache args (apply fn args)))\n (hash-ref cache args))))\n\n(define-syntax-parse-rule (vec! var:id ...)\n (let ()\n (vec1! var) ...))\n\n(define-syntax-parse-rule (vec1! var:id)\n (set! var\n (cond [(string? var) (list->vector (string->list var))]\n [(list? var) (list->vector var)]\n [else var])))\n\n(define (list-sum lst)\n (foldl + 0 lst))\n\n(define in-closed-range in-inclusive-range)\n``` | 1 | 0 | ['Racket'] | 1 |
minimum-time-to-make-array-sum-at-most-x | Actually Helpful Explanation with Proof and Not Just Code translated in English | actually-helpful-explanation-with-proof-cd1f6 | We will find a value MaxRemove[i], this tells us the maximum sum of values we can remove if we can find the answer in i seconds/moves.\n\nIf we can find this Ma | non_deterministic | NORMAL | 2023-08-05T17:09:57.400468+00:00 | 2023-08-05T17:09:57.400491+00:00 | 261 | false | We will find a value MaxRemove[i], this tells us the maximum sum of values we can remove if we can find the answer in i seconds/moves.\n\nIf we can find this MaxRemove[i] for i = 0 to N, then we can just check at every position if the total would be less than X, then we are done.\n\nLet\'s try to find this now.\n\n- There is no point in making one element zero more than once. Because last time when it is made zero, it is zero now, choosing this in any move before this doesn\'t makes sense. This tells us that the maximum number of seconds required is N, otherwise not possible.\n\n- If we have a set of K indexes which we are choosing to make zero at some point, then it is always better to choose the index with the larger num2 value in the end because this will contribute most to the answer otherwise, then second largest in second last position and so on. This tells us that if we try to update our MaxRemove state, it would make sense to iterate from smaller num2 values, as we would know which position to put the latest index in.\n\nNow the idea is initially our set of used indexes is empty. MaxRemove is 0 for all i = 0 to i = N.\nNow we would iterate through the index in increasing order of (num2[i], nums1[i]) and try to update the MaxRemove.\n\nThe state transition is - \nEither take the current element or not.\nIf taken it will present in the last position, so update accordingly.\nMaxRemove[i] = max(MaxRemove[i], MaxRemove[i - 1] + nums1[ind] + nums2[ind] * i);\n\nRefer to my code if something is unclear.\n\n```\n#define all(c) (c).begin(), (c).end()\n\nclass Solution {\npublic:\n int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n int n = nums1.size();\n vector<int> Ind(n, -1);\n iota(all(Ind), 0);\n sort(all(Ind), [&](int i, int j) {\n return make_pair(nums2[i], nums1[i]) < make_pair(nums2[j], nums1[j]);\n });\n vector<int> MaxRemove(n + 1, 0);\n for(auto ind : Ind) {\n for(int i = n; i >= 1; --i) {\n MaxRemove[i] = max(MaxRemove[i], MaxRemove[i - 1] + nums1[ind] + nums2[ind] * i);\n }\n }\n int tot = accumulate(all(nums1), 0);\n int perTurn = accumulate(all(nums2), 0);\n for(int i = 0; i <= n; i++) {\n if(tot + perTurn * i - MaxRemove[i] <= x) return i;\n }\n return -1;\n }\n};\n``` | 1 | 0 | ['C'] | 3 |
minimum-time-to-make-array-sum-at-most-x | [C++] beats 100%, Space complexity: O(N), with explaination | c-beats-100-space-complexity-on-with-exp-mv9s | Intuition\n Describe your first thoughts on how to solve this problem. \n\nTo minimize, we have to find out the minimum num to reset to 0.\n\n# Approach\n Descr | ryankert | NORMAL | 2023-08-05T16:40:07.099894+00:00 | 2023-08-05T16:48:36.552174+00:00 | 164 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nTo minimize, we have to find out the minimum num to reset to 0.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst, we sort `v` (contains `nums2`, `nums1`).\n\nSecond, we use dynamic programming to calcualte the max sum I could deduct(since we can reset) by resets_times.\n`dp[resets_times] = maximum sum I could set to 0 in resets_times`\n\nThen, we find the answer by loop through all possible seconds from `0` sec.\n\n# Complexity\n- Time complexity: $$O(N^2)$$\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 int minimumTime(vector<int>& nums1, vector<int>& nums2, int x) {\n int n = nums1.size(); \n vector<pair<int,int>> v;\n for (int i = 0; i < n; i++) v.push_back({nums2[i], nums1[i]});\n sort(v.begin(), v.end());\n vector<int> dp(n+1, 0);\n for (int j = 0; j < n; j++)\n for (int i = n-1; i >= 0; i--) \n dp[i+1] = max(dp[i+1], dp[i] + v[j].first * (i+1) + v[j].second);\n int n1 = accumulate(nums1.begin(), nums1.end(), 0);\n int n2 = accumulate(nums2.begin(), nums2.end(), 0);\n for (int i = 0; i <= n; i++) \n if (n2 * i + n1 - dp[i] <= x) \n return i;\n return -1;\n }\n};\n``` | 1 | 1 | ['C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | python n2 dynamic programming | python-n2-dynamic-programming-by-hongyil-ntnv | 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 | hongyili | NORMAL | 2023-08-05T16:27:42.745213+00:00 | 2023-08-05T16:27:42.745236+00:00 | 95 | 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)$$ -->\nn^2\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nn\n# Code\n```\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n myl = [(v2, v1) for v1, v2 in zip(nums1, nums2)]\n myl.sort()\n initial = sum(nums1)\n add = sum(nums2)\n myl.sort()\n t = 0\n if initial <= x:\n return t\n n = len(myl)\n mem = [0] * n\n while t < n:\n t += 1\n newmem = [0] * n\n if t == 1:\n newmem[0] = myl[0][0] + myl[0][1]\n for i in range(1, n):\n a, v = myl[i]\n newmem[i] = max(newmem[i-1], mem[i-1]+(v + a*t))\n if initial + add * t - newmem[-1] <= x:\n return t\n mem = newmem\n return -1\n``` | 1 | 0 | ['Dynamic Programming', 'Python3'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Explained DP 33ms | explained-dp-33ms-by-ivangnilomedov-uud2 | IntuitionThe key observation is that when zeroing multiple positions, we want to zero positions with higher growth rates (nums2[i]) later, since they contribute | ivangnilomedov | NORMAL | 2025-01-18T12:43:49.461107+00:00 | 2025-01-18T12:43:49.461107+00:00 | 6 | false | # Intuition
The key observation is that when zeroing multiple positions, we want to zero positions with higher growth rates (nums2[i]) later, since they contribute more to the total sum over time. This leads to a dynamic programming solution where we consider positions in order of their growth rates.
# Approach
The solution uses dynamic programming to track the maximum possible reduction at each step. Key insights that make this work:
1. We never need to zero a position twice - if we zero at times t1 and t2, zeroing only at t2 gives the same result with fewer operations.
2. For optimal reduction, we process positions in order of increasing nums2[i] values. This is provably optimal because swapping the order of operations would result in more growth from higher-rate positions.
The dp array tracks maximum reduction possible using subsets of positions [0..p]. At each step s, for position p, we either:
- Skip position p (take previous best)
- Use p as the last operation (add reduction from initial value + growth over s steps)
We iterate through possible step counts until finding the minimum that achieves the target sum limit.
# Complexity
- Time complexity: $$O(n^2)$$
# Code
```cpp []
class Solution {
public:
/** Core considerations:
* 1. Key insight: Never need to zero a position twice because:
* - If we zero position i twice at t1 < t2
* - The ultimate reduction is same as zeroing only at t2
* 2. For any chosen indices to zero out, it is optimal to process in order
* of increasing nums2[i]; proof: swapping operations in different
* order strictly reduces total reduction */
int minimumTime(vector<int>& nums1, vector<int>& nums2, int sum_lim) {
const int init_sum = accumulate(nums1.begin(), nums1.end(), 0);
if (init_sum <= sum_lim) return 0;
const int addit_sum = accumulate(nums2.begin(), nums2.end(), 0);
const int N = nums1.size();
vector<pair<int, int>> addit_inits(N);
for (int i = 0; i < N; ++i)
addit_inits[i] = { nums2[i], nums1[i] };
sort(addit_inits.begin(), addit_inits.end());
// dp[p] = max reduction possible using subset of positions [0..p]
vector<int> dp(N), up_dp(N);
// For each possible number of steps in solution
for (int s = 1; s <= N; ++s) {
int dp_base = 0, up_dp_base = 0;
int max_up_dp = numeric_limits<int>::min() / 3;
// For each position p, calculate max reduction if [0..p] items considered
for (int p = 0; p < N; ++p) {
up_dp[p] = max(
up_dp_base, // Consider skip zeroing position p
// Or zero it as the very last operation
dp_base + s * addit_inits[p].first + addit_inits[p].second);
dp_base = dp[p];
up_dp_base = up_dp[p];
max_up_dp = max(max_up_dp, up_dp[p]);
}
// Early return if current step count achieves target sum
if (init_sum + s * addit_sum - max_up_dp <= sum_lim) return s;
swap(dp, up_dp);
}
return -1;
}
};
``` | 0 | 0 | ['C++'] | 0 |
minimum-time-to-make-array-sum-at-most-x | DP + Greedy | Intuitive | dp-greedy-intuitive-by-anonymous_k-jurw | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | anonymous_k | NORMAL | 2024-12-24T16:26:04.186360+00:00 | 2024-12-24T16:26:04.186360+00:00 | 12 | 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 minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:
# Intuitive
# We don't need to make one element zero more than once, why? becuase if you're doing so, just skip the first instance where you made it zero, since it was useless.
# We need an order to process, otherwise try all orders and get O(N!)
# With exchange arguments we can tell we should process in nums2 asc order for most reduction or quickly reducing the sum to a lower value.
tup = [(nums2[i], nums1[i]) for i in range(len(nums1))]
tup.sort()
# Now that we have an order, we will need to find an optimal subset that will reduce the running sum to the required value.
# Trying all order == Optimal order + optimal subset.
# Any state involving runningSum will give TLE, since idx / time will be in the state.
# We can try to find the max reduction we can get with t seconds, these t seconds will correspond to the subset we're using.
N = len(nums1) + 1
dp = [[-1] * N for _ in range(N)]
def fn(idx: int, t: int) -> int:
if t == 0: return 0
if idx == -1: return float('-inf')
if dp[idx][t] != -1:
return dp[idx][t]
# ignore, ignoring means no time is used
ans = fn(idx - 1, t)
# take, taking one element corresponds to one second passing
ans = max(ans, tup[idx][1] + t * tup[idx][0] + fn(idx - 1, t - 1))
dp[idx][t] = ans
return ans
s = sum(nums1)
k = sum(nums2)
for t in range(0, len(nums1) + 1):
# Why process tup in reverse order so we can calculate the dp with just two states, we will use the passed t in internal calculation.
# time is same as using t elements.
if s + k * t - fn(len(nums1) - 1, t) <= x:
return t
return -1
``` | 0 | 0 | ['Python3'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Top Down DP || Memoization || Accepted Solution || O(n^2) O(n^2) | top-down-dp-memoization-accepted-solutio-ifg5 | Approach\n Describe your approach to solving the problem. \nI don\'t really like bottom up DP, so I always try me best to come up with top down approach. It is | sulerhy | NORMAL | 2024-09-22T16:47:22.231426+00:00 | 2024-09-22T16:48:56.681241+00:00 | 25 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\nI don\'t really like bottom up DP, so I always try me best to come up with top down approach. It is more natural and easy to explain in the interview. \nYou can also explain the optimal bottom up solution as the follow up later.\nHere is the tip why my code get Accepted:\n1. **@lru_cache(None)**\n2. **if len(nums) - i > time:** only check if there is enough elements left in time\nThese code, I found down in [this solution](https://leetcode.com/problems/minimum-time-to-make-array-sum-at-most-x/solutions/3920367/recursive-solution-o-n-2-beats-nobody)\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n nums = sorted(list(zip(nums2, nums1)), reverse = True)\n @lru_cache(None)\n def dfs(i, time): # return maximum value after "time"\n if time == 0: return 0\n if i == len(nums1): return 0\n # take this number\n speed, start = nums[i]\n local_res = start + speed * time + dfs(i+1, time-1)\n # skip this number, only in the case that there is enough elements left for time\n if len(nums) - i > time:\n local_res = max(local_res, dfs(i+1, time))\n return local_res\n \n sum1 = sum(nums1)\n sum2 = sum(nums2)\n for time in range(len(nums) + 1):\n result = sum1 + time * sum2 - dfs(0, time)\n if result <= x: return time\n return -1\n``` | 0 | 0 | ['Dynamic Programming', 'Memoization', 'Sorting', 'Python3'] | 0 |
minimum-time-to-make-array-sum-at-most-x | Commented | Intuitive | commented-intuitive-by-anonymous_k-e6x3 | 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 | anonymous_k | NORMAL | 2024-09-21T06:54:22.463702+00:00 | 2024-09-21T06:54:22.463742+00:00 | 6 | 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```python3 []\nclass Solution:\n def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n # Intuitive\n # We don\'t neet to make one element zero more than once, why? becuase if you\'re doing so, just skip the first instance where you made it zero, since it was useless.\n # We need an order to process, otherwise try all orders and get O(N!)\n # With exchange arguments we can tell we should process in nums2 asc order for most reduction or quickly reducing the sum to a lower value.\n tup = [(nums2[i], nums1[i]) for i in range(len(nums1))]\n tup.sort()\n # Now that we have an order, we will need to find an optimal subset that will reduce the running sum to the required value. \n # Trying all order == Optimal order + optimal subset.\n # Any state involving runningSum will give TLE, since idx / time will be in the state.\n # We can try to find the max reduction we can get with t seconds, these t seconds will correspond to the subset we\'re using. \n N = len(nums1) + 1\n dp = [[-1] * N for _ in range(N)]\n\n def fn(idx: int, t: int) -> int:\n if t == 0: return 0\n if idx == -1: return float(\'-inf\')\n \n if dp[idx][t] != -1:\n return dp[idx][t]\n\n # ignore, ignoring means no time is used\n ans = fn(idx - 1, t)\n # take, taking one element corresponds to one second passing\n ans = max(ans, tup[idx][1] + t * tup[idx][0] + fn(idx - 1, t - 1))\n dp[idx][t] = ans\n return ans \n\n s = sum(nums1)\n k = sum(nums2)\n for t in range(0, len(nums1) + 1):\n # Why process tup in reverse order so we can calculate the dp with just two states, we will use the passed t in internal calculation.\n if s + k * t - fn(len(nums1) - 1, t) <= x:\n return t\n return -1\n\n\n\n# Old, not so intuitive ----------------------------------------------------------\n res = len(nums1) + 1\n k = sum(nums2)\n tup = [(nums2[i], nums1[i]) for i in range(len(nums1))]\n tup.sort()\n dp = [[0] * res for _ in range(res)]\n \n for idx in range(1, res):\n for t in range(1, idx + 1):\n dp[idx][t] = max(dp[idx - 1][t], dp[idx - 1][t - 1] + tup[idx - 1][1] + t * tup[idx - 1][0])\n \n s = sum(nums1)\n for t in range(0, res):\n if s + k * t - dp[-1][t] <= x:\n res = min(res, t)\n\n return res if res <= len(nums1) else -1\n\n# Previous TLE\n# class Solution:\n# def minimumTime(self, nums1: List[int], nums2: List[int], x: int) -> int:\n# res = len(nums1) + 1\n# k = sum(nums2)\n# tup = [(nums2[i], nums1[i]) for i in range(len(nums1))]\n# tup.sort()\n# print(tup)\n# dp = {}\n\n# def fn(idx: int, s: int, t: int):\n# nonlocal res\n# if s <= x:\n# res = min(res, t)\n# return\n# if idx >= len(nums1):\n# return\n \n# key = (idx, s, t)\n# if key in dp:\n# return\n \n# # take \n# fn(idx + 1, s + k - tup[idx][1] - (t + 1) * tup[idx][0], t + 1)\n# # leave\n# fn(idx + 1, s, t)\n# dp[key] = True\n \n# fn(0, sum(nums1), 0)\n# return res if res <= len(nums1) else -1\n\n``` | 0 | 0 | ['Python3'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.