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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
maximize-happiness-of-selected-children | Easy to Understand || brute force || solution without using greedy algo | easy-to-understand-brute-force-solution-sgfxk | \n\nclass Solution {\npublic:\n long long maximumHappinessSum(vector<int>& happiness, int k) {\n sort(happiness.begin(),happiness.end()); // sorting s | divyanxsh | NORMAL | 2024-05-13T14:39:48.961585+00:00 | 2024-05-13T14:40:14.661565+00:00 | 4 | false | \n```\nclass Solution {\npublic:\n long long maximumHappinessSum(vector<int>& happiness, int k) {\n sort(happiness.begin(),happiness.end()); // sorting so that the happiest child is at the last index\n long long int ans= 0;\n int count=0;\n int size= happiness.size();\n while(count<k){\n int temp= happiness.at(size-1); \n happiness.pop_back();\n if(temp>0 && temp>=count){\n ans= ans+ (temp-count); // with every count other children\'s happiness drops by 1\n count++;\n size--;\n }\n else{\n return ans;\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximize-happiness-of-selected-children | ✅ C#, Beginner Friendly, Beats %94 ✅ | c-beginner-friendly-beats-94-by-msoykann-0m43 | Intuition\n Describe your first thoughts on how to solve this problem. \nWe simply need to find n highest values inside the given array.\n\n# Approach\n Describ | MSoykann | NORMAL | 2024-05-10T13:46:14.806025+00:00 | 2024-05-17T10:28:43.046185+00:00 | 15 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe simply need to find n highest values inside the given array.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nFirst we sort the happiness list. In order to maximize our happiness score we start picking values from the end of the array. In order to satisfy the following line:\n\n"*n each turn, when you select a child, the happiness value of all the children that have not been selected till now decreases by 1. Note that the happiness value cannot become negative and gets decremented only if it is positive*."\n\n At each step of chosing a number, we decrement the picked value with respect to the #(count) of numbers picked. We take the Max value of 0 and pickedHappinessValue so that our happiness value doesn\'t go below 0 after decrementing it.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn) (Array.Sort function uses introsort with O(nlogn))\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n\n# Code\n```\npublic class Solution {\n public long MaximumHappinessSum(int[] happiness, int k) {\n if(happiness.Length<k) return -1; // handle edge-case\n Array.Sort(happiness);\n long sum=0;\n for(int i=0;i<k;i++){\n sum+=Math.Max(0,happiness[happiness.Length-1-i]-i);\n }\n return sum;\n }\n}\n``` | 1 | 0 | ['Sorting', 'C#'] | 0 |
maximize-happiness-of-selected-children | Another day another 1 liner | another-day-another-1-liner-by-santoshvi-mwi2 | Intuition\n Describe your first thoughts on how to solve this problem. \n## Greeeeeeedyyyy\n\n\n# Approach\n Describe your approach to solving the problem. \n- | santoshvijapure | NORMAL | 2024-05-09T18:37:59.235465+00:00 | 2024-05-09T18:37:59.235497+00:00 | 14 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n## Greeeeeeedyyyy\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- sort them in decreasing order\n- slice em from 0 to k \n- calculate the sum of all numbers in sliced array and reduce them by i or take 0 if numnber is negative\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(NlogN)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nO(N)\n# Code\n```\n/**\n * @param {number[]} happiness\n * @param {number} k\n * @return {number}\n */\nvar maximumHappinessSum = function (happiness, k) {\n\n return happiness.sort((a, b) => b - a).slice(0, k).reduce((ac, n, i) => ac + Math.max(n-i,0), 0)\n\n};\n```\n\n\n\n\n\n | 1 | 0 | ['Greedy', 'Sorting', 'JavaScript'] | 1 |
maximize-happiness-of-selected-children | Beats 99% | O(n + k*logk) runtime and O(1) space | beats-99-on-klogk-runtime-and-o1-space-b-606q | Intuition\nSelect the children with the max happiness to maximize the sum of the happiness.\n\n# Approach\nAvoid sorting of the very happy children with happine | sanjok | NORMAL | 2024-05-09T18:37:40.920431+00:00 | 2024-05-09T19:10:24.329056+00:00 | 17 | false | # Intuition\nSelect the children with the max happiness to maximize the sum of the happiness.\n\n# Approach\nAvoid sorting of the very happy children with $$happiness > K$$.\nAvoid sorting of the unhappy children. All of them will be zeroed.\n\n# Complexity\n- Time complexity: $$O(n + k*logk)$$ on average\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumHappinessSum(vector<int>& happiness, int k)\n {\n // remove n-k smallest children. they are not calculated\n // runtime O(n) on average\n nth_element(happiness.begin(), happiness.begin() + k, happiness.end(), greater<>());\n happiness.resize(k); // runtime O(1)\n // number of elements is k now\n\n // divide the rest into 2 groups, when the first group is greater than k.\n // the first group should not be sorted.\n // runtime O(k)\n auto smallIter = partition(happiness.begin(), happiness.end(), [k](int i) {return i >= k;});\n \n long long sum = 0;\n\n // calculate the first group\n auto iter = happiness.begin();\n // runtime O(first group) <= O(k)\n for (int i = 0; iter < smallIter; ++i, ++iter)\n {\n sum += *iter - i;\n }\n\n // part of the second group will be zeroed at some point.\n // create max-heap to find the not zeroed ones.\n // runtime O(second group) <= O(k)\n make_heap(smallIter, happiness.end());\n\n // runtime O(non-zeroed in the second group) <= O(k) iterations of O(log(second group))\n // ==> O(k*logk)\n for (int i = smallIter - happiness.begin();\n i < k\n && *smallIter > i; // stop when all the rest are zeroed\n ++i)\n {\n sum += *smallIter - i;\n pop_heap(smallIter, happiness.end()); // O(log(second group)) <= O (logK)\n happiness.pop_back(); // runtime O(1)\n }\n\n return sum;\n }\n};\n``` | 1 | 0 | ['Heap (Priority Queue)', 'C++'] | 0 |
maximize-happiness-of-selected-children | Simple JAVA Solution || Sorting and turns || Greedy | simple-java-solution-sorting-and-turns-g-zqvv | 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 | saad_hussain_ | NORMAL | 2024-05-09T18:20:34.546601+00:00 | 2024-05-09T18:20:34.546650+00:00 | 1 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(NlogN)\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 long maximumHappinessSum(int[] hap, int k) {\n Arrays.sort(hap);\n int len=hap.length;\n int turns=0;\n long sum=0;\n for(int i=len-1;i>=0;i--){\n sum=sum+Math.max(0,hap[i]-turns);\n turns++;\n if(turns>=k) break;\n \n }\n return sum;\n }\n}\n``` | 1 | 0 | ['Greedy', 'Java'] | 0 |
maximize-happiness-of-selected-children | Maximizing Happiness Sum: Selecting Children in Turns | maximizing-happiness-sum-selecting-child-sjdn | Intuition\nTo maximize the sum of happiness values while selecting children, we should prioritize selecting children with higher initial happiness values.\n Des | janhvipandey | NORMAL | 2024-05-09T17:59:59.843646+00:00 | 2024-05-09T17:59:59.843677+00:00 | 0 | false | # Intuition\nTo maximize the sum of happiness values while selecting children, we should prioritize selecting children with higher initial happiness values.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Sort the array of happiness values in non-decreasing order.\n2. Iterate through the sorted array from the end and select the children with the highest happiness values.\n3. Decrement the happiness values of unselected children by the number of turns taken.\n4. Repeat this process for k turns.\n5. Sum up the happiness values of the selected children and return the total sum.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n log n) due to sorting, where n is the number of children.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1) since we only use a constant amount of extra space for variables.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumHappinessSum(vector<int>& happiness, int k) {\n sort(happiness.begin(), happiness.end());\n int n=happiness.size();\n long long ans=0;\n for(int i=0; i<k; i++){\n if(happiness[n-i-1]-i>0){\n ans+=happiness[n-i-1]-i;\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
maximize-happiness-of-selected-children | Easiest approach with sorting | easiest-approach-with-sorting-by-zhiyang-epav | Intuition\n Describe your first thoughts on how to solve this problem. \nGreedily select the first k largest element and/or stop until you see the first 0.\n\n# | ZhiYangLim | NORMAL | 2024-05-09T17:47:07.068441+00:00 | 2024-05-09T18:07:17.559863+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGreedily select the first $$k$$ largest element and/or stop until you see the first $$0$$.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. sort `happiness` in descending order\n2. initialize `max=0` to keep track of max later and to return\n3. have a loop looping through the element from high to low\n4. minus `i` for each `happiness[i]` as it will be encounterd after ith step. \n5. If `happiness[i] - i <= 0` or `k == 0` break, as we will not making more progress to increase the max\n6. For each step, we increase max by `happiness[i] - i` and decrement `k`\n7. return `max`\n\n# Complexity\n- Time complexity: $$O(n log n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ sorting for python takes $$O(n)$$ additional space\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maximumHappinessSum(self, happiness: List[int], k: int) -> int:\n happiness.sort(reverse=True)\n max = 0\n for i in range(len(happiness)):\n if (happiness[i] - i <= 0 or k == 0):\n break\n max += happiness[i] - i\n k -= 1\n\n\n return max\n\n``` | 1 | 0 | ['Array', 'Greedy', 'Sorting', 'Python3'] | 1 |
maximize-happiness-of-selected-children | Swift solution | swift-solution-by-azm819-sp8x | Complexity\n- Time complexity: O(n * log(n))\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) | azm819 | NORMAL | 2024-05-09T17:27:14.800070+00:00 | 2024-05-09T17:27:14.800104+00:00 | 9 | false | # Complexity\n- Time complexity: $$O(n * log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n func maximumHappinessSum(_ happiness: [Int], _ k: Int) -> Int {\n let hapiness = happiness.sorted(by: >)\n var result = 0\n for i in 0 ..< min(hapiness.count, k) {\n let subRes = hapiness[i] - i\n if subRes <= .zero {\n break\n }\n result += subRes\n }\n return result\n }\n}\n``` | 1 | 0 | ['Array', 'Greedy', 'Swift', 'Sorting'] | 0 |
maximize-happiness-of-selected-children | Easy and Efficient Approach | easy-and-efficient-approach-by-vedantdap-mc2z | \n\n# Approach\nWe first sort the happiness vector in descending order\nand then consider the elements that give maximum happiness value.\n\n# Complexity\n- Tim | vedantdapolikar18 | NORMAL | 2024-05-09T16:54:49.556355+00:00 | 2024-05-09T16:54:49.556387+00:00 | 8 | false | \n\n# Approach\nWe first sort the happiness vector in descending order\nand then consider the elements that give maximum happiness value.\n\n# Complexity\n- Time complexity:\n$$O(nlogn)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n long long maximumHappinessSum(vector<int>& happiness, int k) {\n sort(happiness.begin(),happiness.end());\n int n = happiness.size();\n int i = 0 ;\n long long ans = 0 ;\n while(i < k){\n if(happiness[n-i-1]-i >= 0){\n ans += happiness[n-i-1] - i ;\n }\n i++ ;\n }\n return ans ;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | O(N^2) and O(N) solutions explained. | on2-and-on-solutions-explained-by-stomac-6qnk | Intuition\nPick an index to eliminate (-1 for none) and keep track of best score. In the inner loop d is the current gcd, m is the current lcm. Note that: gcd(0 | stomachion | NORMAL | 2024-10-27T04:36:42.544604+00:00 | 2024-10-27T05:30:12.972247+00:00 | 1,655 | false | # Intuition\nPick an index to eliminate (-1 for none) and keep track of best score. In the inner loop `d` is the current **gcd**, `m` is the current **lcm**. Note that: `gcd(0, x) = x` and `lcm(1, x) = x`.\n\nSince N is small (up to 100) the brute force $$O(N^2)$$ solution is very fast. For larger values of N (up to $$10^5$$) is worth using a bit of extra memory to improve time efficiency to $$O(N)$$.\n\nSee the second solution which uses prefix and suffix arrays for **gcd** and **lcm**. To calculate `gcd` without index `i` = `gcd(dpre[i-1], dsuf[i+1])`, rather then looping through the remaining n-1 indexes (and similarly for `lcm`).\n\nEven for the small values tested for this problem the second solution is faster then the first `6ms` versus `55ms`.\n\n\n# Code\n**Solution 1**\nTime complexity: $$O(N^2)$$, Space complexity: $$O(1)$$\n```\ndef maxScore(self, nums: List[int]) -> int:\n n = len(nums)\n res = 0\n for i in range(-1, n):\n d, m = 0, 1\n for j in range(n):\n if j != i:\n d = gcd(d, nums[j])\n m = lcm(m, nums[j])\n res = max(res, d * m)\n return res\n```\n\n**Solution 2**\nTime complexity: $$O(N)$$, Space complexity: $$O(N)$$\n\n```\ndef maxScore(self, nums: List[int]) -> int:\n def incremental(index_order):\n darr, marr = [0] * n, [0] * n\n d, m = 0, 1\n for i in index_order:\n d = gcd(d, nums[i])\n m = lcm(m, nums[i])\n darr[i], marr[i] = d, m\n return darr, marr\n\n n = len(nums)\n dpre, mpre = incremental(range(n))\n dsuf, msuf = incremental(reversed(range(n)))\n res = dpre[-1] * mpre[-1]\n for i in range(n):\n d1, d2 = dpre[i - 1] if i > 0 else 0, dsuf[i + 1] if i + 1 < n else 0\n m1, m2 = mpre[i - 1] if i > 0 else 1, msuf[i + 1] if i + 1 < n else 1\n res = max(res, gcd(d1, d2) * lcm(m1, m2))\n return res\n``` | 16 | 0 | ['Python3'] | 2 |
find-the-maximum-factor-score-of-array | C# Short and simple | c-short-and-simple-by-connectedpuddle-g0c7 | Intuition\n\nCheck all cases of which number if any is excluded. Compute the factor score in each case.\n\nexclude = -1 means no number is excluded.\n\nlcm is i | ConnectedPuddle | NORMAL | 2024-10-27T05:08:54.675470+00:00 | 2024-10-27T05:08:54.675498+00:00 | 701 | false | # Intuition\n\nCheck all cases of which number if any is excluded. Compute the factor score in each case.\n\n`exclude = -1` means no number is excluded.\n\n`lcm` is initialised to 1 because $LCM(1, x) = x$ for all $x$\n\n`gcd` is initialised to 0 because $GCD(0, x) = x$ for all $x$\n\n\n# Complexity\n- Time complexity: $O(n^2)$ \n\n- Space complexity: $O(1)$\n\n# Code\n```csharp []\npublic class Solution {\n public long MaxScore(int[] nums) {\n int n = nums.Length;\n long result = 0;\n for (int exclude = -1; exclude < n; exclude++)\n {\n long lcm = 1;\n long gcd = 0;\n for (int i = 0; i < n; i++)\n {\n if (i == exclude)\n {\n continue;\n }\n lcm = LCM(lcm, nums[i]);\n gcd = GCD(gcd, nums[i]);\n }\n result = Math.Max(result, lcm * gcd);\n }\n return result;\n }\n\n public long GCD(long x, long y)\n {\n while (x > 0 && y > 0)\n {\n if (x > y)\n {\n x %= y;\n }\n else\n {\n y %= x;\n }\n }\n return x | y;\n }\n\n public long LCM(long x, long y)\n {\n return x * y / GCD(x, y);\n }\n}\n``` | 14 | 0 | ['Number Theory', 'C#'] | 1 |
find-the-maximum-factor-score-of-array | Python3 || Two eight-line versions || T/S: 99% / 89% | python3-two-eight-line-versions-ts-99-89-mx9u | \n### Brute Force with an optimization version:\nHere\'s the intuition:\n- The problem\'s constraints allow for acceptable O(N^2) solutions.\n\n- The constraint | Spaulding_ | NORMAL | 2024-10-27T17:22:30.246934+00:00 | 2024-10-29T20:05:37.598350+00:00 | 466 | false | \n### Brute Force with an optimization version:\nHere\'s the intuition:\n- The problem\'s constraints allow for acceptable *O*(*N*^2) solutions.\n\n- The constraints also permit significant optimization in using *Counter* to filter the elements of `nums` so that we only test the *unique* elements of `nums`.\n\n```python3 []\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n\n n, ctr = len(nums), Counter(nums)\n\n mx = gcd(*nums) * lcm(*nums)\n \n if n > 1:\n\n for i in range(n):\n if ctr[nums[i]] > 1: continue\n\n arr = nums[:i] + nums[i+1:]\n mx = max(mx, gcd(*arr) * lcm(*arr))\n \n return mx\n```\n___\n\n### Prefix version:\n\nHere\'s the intuition:\n\n- We use `accumulate` to build *prefix* lists. \n- We zip these lists and `nums` to facilitate iterating the *lcm-gcd* products.\n- We return the maximum of these products as the answer.\n\n```python3 []\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n\n n, lcm_, gcd_ = len(nums), 1, 0\n ans = gcd(*nums) * lcm(*nums)\n\n pref_lcm = list(accumulate(nums[n-1:0:-1], lcm, initial = 1))[::-1]\n pref_gcd = list(accumulate(nums[n-1:0:-1], gcd, initial = 0))[::-1]\n\n for pref_lcm, pref_gcd, num in zip(pref_lcm, pref_gcd, nums):\n \n ans = max(ans, lcm(lcm_, pref_lcm) * gcd(gcd_, pref_gcd))\n lcm_, gcd_ = lcm(lcm_, num), gcd(gcd_, num)\n\n return ans\n```\n[https://leetcode.com/problems/find-the-maximum-factor-score-of-array/submissions/1435402519/\n](https://leetcode.com/problems/find-the-maximum-factor-score-of-array/submissions/1435402519/\n)\nI could be wrong, but I think that time complexities is *O*(*N*^2) and space complexity is *O*(*N*), in which *N* ~ `len(nums)`.\n | 13 | 1 | ['Python3'] | 2 |
find-the-maximum-factor-score-of-array | Max Score with Brute Force ✅🔥: GCD and LCM Solutions | max-score-with-brute-force-gcd-and-lcm-s-iw2u | Approach\n\nJUST FINDING ALL POSSIBLE SOLUTION \n\n# Complexity\n- Time complexity:\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:\n Add you | ankit_kumar12345 | NORMAL | 2024-10-27T04:03:38.990401+00:00 | 2024-10-27T12:38:41.592690+00:00 | 3,622 | false | # Approach\n\nJUST FINDING ALL POSSIBLE SOLUTION \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```cpp []\n#include <vector>\n#include <algorithm>\n#include <numeric>\n\nclass Solution {\npublic:\n long long get(vector<int>& nums, int x) {\n long long ans = 0;\n int n = nums.size();\n\n long long gcd = (x != 0) ? nums[0] : nums[1];\n long long lcm = gcd;\n\n for (int i = (x == 0 ? 2 : 1); i < n; ++i) {\n if (i == x) continue;\n int a = nums[i];\n gcd = __gcd(gcd, (long long)a);\n lcm = (lcm * a) / __gcd(lcm, (long long)a);\n }\n\n return gcd * lcm;\n }\n\n long long maxScore(vector<int>& nums) {\n int n = nums.size();\n if (n == 1) return (long long)nums[0] * nums[0];\n\n long long maxi = get(nums, -1);\n\n for (int i = 0; i < n; ++i) {\n maxi = max(maxi, get(nums, i));\n }\n\n return maxi;\n }\n};\n\n```\n```javascript []\nclass Solution {\n gcd(a, b) {\n return b === 0 ? a : this.gcd(b, a % b);\n }\n\n get(nums, x) {\n let n = nums.length;\n\n let gcd = (x !== 0) ? nums[0] : nums[1];\n let lcm = gcd;\n\n for (let i = (x === 0 ? 2 : 1); i < n; ++i) {\n if (i === x) continue;\n let a = nums[i];\n gcd = this.gcd(gcd, a);\n lcm = (lcm * a) / this.gcd(lcm, a);\n }\n\n return gcd * lcm;\n }\n\n maxScore(nums) {\n let n = nums.length;\n if (n === 1) return nums[0] * nums[0];\n\n let maxi = this.get(nums, -1);\n\n for (let i = 0; i < n; ++i) {\n maxi = Math.max(maxi, this.get(nums, i));\n }\n\n return maxi;\n }\n}\n\n```\n```python []\nfrom math import gcd\nfrom functools import reduce\n\nclass Solution:\n def get(self, nums, x):\n n = len(nums)\n\n gcd_val = nums[0] if x != 0 else nums[1]\n lcm_val = gcd_val\n\n for i in range(2 if x == 0 else 1, n):\n if i == x:\n continue\n a = nums[i]\n gcd_val = gcd(gcd_val, a)\n lcm_val = (lcm_val * a) // gcd(lcm_val, a)\n\n return gcd_val * lcm_val\n\n def maxScore(self, nums):\n n = len(nums)\n if n == 1:\n return nums[0] * nums[0]\n\n maxi = self.get(nums, -1)\n\n for i in range(n):\n maxi = max(maxi, self.get(nums, i))\n\n return maxi\n\n```\n```java []\nimport java.util.List;\n\nclass Solution {\n private long get(List<Integer> nums, int x) {\n long ans = 0;\n int n = nums.size();\n\n long gcd = (x != 0) ? nums.get(0) : nums.get(1);\n long lcm = gcd;\n\n for (int i = (x == 0 ? 2 : 1); i < n; ++i) {\n if (i == x) continue;\n int a = nums.get(i);\n gcd = gcd(gcd, a);\n lcm = (lcm * a) / gcd(lcm, a);\n }\n\n return gcd * lcm;\n }\n\n public long maxScore(List<Integer> nums) {\n int n = nums.size();\n if (n == 1) return (long) nums.get(0) * nums.get(0);\n\n long maxi = get(nums, -1);\n\n for (int i = 0; i < n; ++i) {\n maxi = Math.max(maxi, get(nums, i));\n }\n\n return maxi;\n }\n\n private long gcd(long a, long b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n}\n\n```\n | 10 | 2 | ['C++', 'Java', 'Python3', 'JavaScript'] | 4 |
find-the-maximum-factor-score-of-array | 🥁EASY SOLUTION EXPLAINED | easy-solution-explained-by-ramitgangwar-jt0s | \n\n# \uD83D\uDC93**_PLEASE CONSIDER UPVOTING_**\uD83D\uDC93\n\n \n\n\n\n# \u2B50 Intuition\nThe goal is to maximize the "factor score," defined as the product | ramitgangwar | NORMAL | 2024-10-28T06:22:33.504570+00:00 | 2024-10-28T06:22:33.504607+00:00 | 248 | false | <div align="center">\n\n# \uD83D\uDC93**_PLEASE CONSIDER UPVOTING_**\uD83D\uDC93\n\n</div>\n\n***\n\n# \u2B50 Intuition\nThe goal is to maximize the "factor score," defined as the product of the array\'s GCD and LCM, after potentially removing one element. Calculating the factor score for different subsets of the array (where each subset excludes one element) allows us to find the maximum possible score.\n\n# \u2B50 Approach\n1. **Calculate Initial GCD and LCM**:\n - Compute the GCD and LCM of the entire array to establish a baseline factor score. This score is used as one possible answer.\n2. **Check Factor Scores with Each Element Removed**:\n - For each element in the array, calculate the GCD and LCM of the subset of the array that excludes that element.\n - Compute the factor score for this subset and update the maximum score if this factor score is higher.\n3. **Return the Maximum Score**:\n - After calculating scores with each element excluded, return the maximum factor score found.\n\n# \u2B50 Complexity\n- **Time Complexity**: $$O(n^2)$$, as we need to calculate the GCD and LCM while iterating over each possible subset.\n- **Space Complexity**: $$O(1)$$, aside from the input and output storage, as we only store a few auxiliary variables.\n\n# \u2B50 Code\n```java []\nclass Solution {\n public long gcd(long a, long b) {\n if (b == 0) return a;\n return gcd(b, a % b);\n }\n\n public long lcm(long a, long b) {\n return (a * b) / gcd(a, b);\n }\n\n public long maxScore(int[] arr) {\n long arrayGCD = 0;\n long arrayLCM = 1;\n\n for (int num : arr) {\n arrayGCD = gcd(arrayGCD, num);\n arrayLCM = lcm(arrayLCM, num);\n }\n\n long maxFactor = arrayGCD * arrayLCM;\n\n for (int i = 0; i < arr.length; i++) {\n long subGCD = 0;\n long subLCM = 1;\n\n for (int j = 0; j < arr.length; j++) {\n if (i != j) {\n subGCD = gcd(subGCD, arr[j]);\n subLCM = lcm(subLCM, arr[j]);\n }\n }\n\n maxFactor = Math.max(maxFactor, subGCD * subLCM);\n }\n\n return maxFactor;\n }\n}\n``` | 6 | 0 | ['Math', 'Java'] | 0 |
find-the-maximum-factor-score-of-array | Brute Force + Prefix and Suffix Array | brute-force-prefix-and-suffix-array-by-z-m3g7 | Intuition\n Describe your first thoughts on how to solve this problem. \nSince we have the property that gcd(a,b,c) = gcd (gcd(a,b),c), and same for lcm, we can | ZiwenLiu35 | NORMAL | 2024-10-27T05:54:52.307062+00:00 | 2024-10-27T05:54:52.307088+00:00 | 596 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nSince we have the property that gcd(a,b,c) = gcd (gcd(a,b),c), and same for lcm, we can build prefix and suffix gcd and lcm array to store these value beforehand.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nloop through the array with skip index, the score after removal is gcd * lcm of (prefix[skip -1] and sufix[skip+1]). Maintain the maxScore after each loop.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ --> O(nlogn)\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n# Code\n```java []\nclass Solution {\n public long findGcd(long a, long b){\n while (b != 0){\n long temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n }\n public long findLcm(long a, long b){ \n return (a * b) / findGcd(a,b);\n }\n public long maxScore(int[] nums) {\n int n = nums.length;\n if (n == 0) {\n return 0;\n }\n if (n == 1){\n return nums[0]*nums[0];\n }\n long[] preGcd = new long[n];\n long[] sufGcd = new long[n];\n long[] preLcm = new long[n];\n long[] sufLcm = new long[n];\n\n preGcd[0] = nums[0];\n sufGcd[n-1] = nums[n-1];\n preLcm[0] = nums[0];\n sufLcm[n-1] = nums[n-1];\n\n for (int i = 1; i < n; i++){\n preGcd[i] = findGcd(preGcd[i-1], nums[i]);\n \n preLcm[i] = findLcm(preLcm[i-1], nums[i]);\n }\n\n for (int i = n - 2; i >= 0; i--){\n sufGcd[i] = findGcd(sufGcd[i+1], nums[i]);\n sufLcm[i] = findLcm(sufLcm[i+1], nums[i]);\n //system.out.println("suf gcd and sf lcm is :" +sufGcd[1] + " "+ sufLcm[1]);\n }\n\n long maxScore = preGcd[n-1] * preLcm[n-1];\n\n for (int skip = 0; skip < n;skip++){\n long currScore;\n if (skip == 0){\n currScore = sufGcd[1] * sufLcm[1];\n //System.out.println(sufGcd[1] + " "+ sufLcm[1]);\n maxScore = Math.max(maxScore, currScore);\n //System.out.println("currScore is :" + currScore);\n continue;\n }\n if (skip == n - 1){\n currScore = preGcd[n-2] * preLcm[n-2];\n maxScore = Math.max(maxScore, currScore);\n continue;\n }\n long gcd = findGcd(preGcd[skip-1], sufGcd[skip+1]);\n long lcm = findLcm(preLcm[skip-1], sufLcm[skip+1]);\n currScore = gcd * lcm; \n maxScore = Math.max(maxScore, currScore);\n }\n return maxScore;\n }\n}\n``` | 6 | 0 | ['Java'] | 2 |
find-the-maximum-factor-score-of-array | Java Easy and Clearn Solution ( Explained ) | java-easy-and-clearn-solution-explained-yvt7q | Solution\njava []\nclass Solution {\n public long gcd(long a, long b) {\n while(b!=0){\n long temp =b;\n b = a%b;\n a | moazmar | NORMAL | 2024-11-01T21:53:57.249130+00:00 | 2024-11-01T21:53:57.249180+00:00 | 306 | false | # Solution\n```java []\nclass Solution {\n public long gcd(long a, long b) {\n while(b!=0){\n long temp =b;\n b = a%b;\n a = temp;\n }\n return a;\n }\n\n public long lcm(long a, long b) {\n return a*b / gcd(a,b);\n }\n\n public long gcdOfArray(int[] arr){\n long res = arr[0];\n for(int i=1; i<arr.length;i++){\n res = gcd(res, arr[i]);\n }\n return res;\n }\n\n public long lcmOfArray(int[] arr){\n long res = arr[0];\n for(int i=1;i<arr.length;i++){\n res = lcm(res,arr[i]);\n }\n return res;\n }\n\n public int[] subArray(int[] arr , int index, int n){\n int[] res = new int[n - 1];\n for(int i=0, j=0; i<n; i++){\n if(i==index)continue;\n res[j++]=arr[i];\n }\n return res;\n }\n\n public long maxScore(int[] nums) {\n int n = nums.length;\n long res = lcmOfArray(nums)*gcdOfArray(nums);\n if(n==1)return res;\n for(int i=0;i<n;i++){\n int[] sub = subArray(nums, i, n);\n res = Math.max(res,lcmOfArray(sub)*gcdOfArray(sub));\n }\n \n return res;\n }\n}\n```\n\n### Example Execution\n\nSuppose you call `maxScore` with an array like `[2, 4, 6]`:\n- It computes the LCM and GCD for the entire array.\n- It then generates subarrays such as `[4, 6]`, `[2, 6]`, and `[2, 4]`, calculating their LCMs and GCDs.\n- It compares all computed scores and returns the maximum.\n\n\n### Method Breakdown\n\n1. **`gcd(long a, long b)`**:\n - This method computes the GCD of two numbers using the Euclidean algorithm.\n - **How it works**:\n - While `b` is not zero, it performs the following:\n - Stores the value of `b` in a temporary variable (`temp`).\n - Sets `b` to `a % b` (the remainder of `a` divided by `b`).\n - Updates `a` to the value of `temp` (the previous value of `b`).\n - When `b` becomes zero, `a` holds the GCD of the two numbers, which is returned.\n\n2. **`lcm(long a, long b)`**:\n - This method calculates the LCM of two numbers.\n - **How it works**:\n - The formula used is \\( \\text{lcm}(a, b) = \\frac{a \\times b}{\\text{gcd}(a, b)} \\).\n - It first computes the GCD of `a` and `b`, then multiplies `a` and `b`, and divides the product by the GCD to get the LCM.\n\n3. **`gcdOfArray(int[] arr)`**:\n - This method calculates the GCD of an entire array of integers.\n - **How it works**:\n - Initializes a variable `res` with the first element of the array.\n - Iterates through the rest of the array, updating `res` to the GCD of the current `res` and the next element in the array.\n - Returns the final GCD of the entire array.\n\n4. **`lcmOfArray(int[] arr)`**:\n - This method calculates the LCM of an entire array of integers.\n - **How it works**:\n - Similar to `gcdOfArray`, it initializes `res` with the first element.\n - Iterates through the rest of the array, updating `res` to the LCM of the current `res` and the next element.\n - Returns the final LCM of the entire array.\n\n5. **`subArray(int[] arr, int index, int n)`**:\n - This method creates a new array that excludes the element at the specified `index`.\n - **How it works**:\n - Initializes a new array `res` of size `n - 1` (to account for one fewer element).\n - Iterates through the original array, copying elements to `res`, skipping the element at `index`.\n - Returns the resulting subarray.\n\n6. **`maxScore(int[] nums)`**:\n - This is the main method that calculates the maximum score based on the LCM and GCD of subarrays.\n - **How it works**:\n - Initializes `n` as the length of the input array `nums`.\n - Computes the initial score as the product of the LCM and GCD of the entire array.\n - If the array has only one element, it returns that score directly.\n - Iterates through each index of the array, generates a subarray excluding the element at that index, and calculates the LCM and GCD of that subarray.\n - Updates `res` to be the maximum score found by comparing it to the current score.\n - Finally, it returns the maximum score.\n\n | 5 | 0 | ['Java'] | 1 |
find-the-maximum-factor-score-of-array | Calculate Prefix and Suffix for both lcm and gcd | calculate-prefix-and-suffix-for-both-lcm-qi7y | Intuition\nWe can calculate prefix and suffix arrays for gcd and lcm as they\'re both associative.\n\n# Approach\n- For array size n \n - if n = 0 return 0 as | sriharivishnu | NORMAL | 2024-10-27T06:28:35.946558+00:00 | 2024-10-27T06:28:35.946588+00:00 | 728 | false | # Intuition\nWe can calculate prefix and suffix arrays for gcd and lcm as they\'re both associative.\n\n# Approach\n- For array size $$n$$ \n - if $$n = 0$$ return $$0$$ as mentioned in the problem\n - Else if $$n = 1$$ return $$nums[0] * nums[0]$$ as $$nums[0]$$ as lcm and gcd of a number is itself\n - Else, proceed with the steps below\n- Calculate prefix and suffix arrays for lcm and gcd\n- Calculate the result without removing any elements as\n - $$postlcm[0] * postgcd[0]$$ or $$prelcm[n-1] * pregcd[n - 1]$$\n- Calculate value without index for $$i \\text{ for } i = 1, \\ldots, n - 2$$ \n - $$lcm = lcm(prelcm[i - 1], postlcm[i + 1])$$\n - $$gcd = gcd(pregcd[i - 1], postgcd[i + 1])$$\n - $$value = lcm * gcd$$\n- For $$i = 0$$ or $$i = n - 1$$\n - $$i = 0$$: $$postlcm[1] * postgcd[1]$$\n - $$i = n - 1$$: $$prelcm[n - 2] * pregcd[n - 2]$$\n\n# Complexity\n- Time complexity: $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long maxScore(vector<int>& nums) {\n int n = nums.size();\n if (n == 0) return 0;\n if (n == 1) return nums[0] * nums[0];\n\n vector<int> pregcd(n, 0), postgcd(n, 0);\n vector<long long> prelcm(n, 0), postlcm(n, 0);\n pregcd[0] = prelcm[0] = nums[0];\n\n --n;\n for (int i = 1; i <= n; ++i) {\n pregcd[i] = gcd(nums[i], pregcd[i - 1]);\n prelcm[i] = lcm(prelcm[i - 1], nums[i]);\n }\n \n postgcd[n] = postlcm[n] = nums[n];\n for (int i = n - 1; i >= 0; --i) { \n postgcd[i] = gcd(nums[i], postgcd[i + 1]);\n postlcm[i] = lcm(postlcm[i + 1], nums[i]);\n }\n \n long long res = max(\n max(postlcm[0] * postgcd[0], postlcm[1] * postgcd[1]),\n prelcm[n - 1] * pregcd[n - 1]\n );\n \n long long cur;\n for (int i = 1; i < n; ++i) {\n cur = lcm(prelcm[i - 1], postlcm[i + 1]) *\n gcd(pregcd[i - 1], postgcd[i + 1]);\n res = max(cur, res);\n }\n\n return res;\n }\n};\n``` | 5 | 0 | ['C++'] | 1 |
find-the-maximum-factor-score-of-array | "Medium"? Ridiculous. (Python, 5 lines) | medium-ridiculous-python-5-lines-by-stef-2cwh | It\'s an "Easy" problem.\n\n def maxScore(self, nums: List[int]) -> int:\n return max(\n lcm(a) * gcd(a)\n for i in range(len(nu | stefanpochmann | NORMAL | 2024-10-28T20:41:08.703062+00:00 | 2024-10-28T20:50:42.603091+00:00 | 127 | false | It\'s an "Easy" problem.\n\n def maxScore(self, nums: List[int]) -> int:\n return max(\n lcm(*a) * gcd(*a)\n for i in range(len(nums) + 1)\n for a in [nums[:i] + nums[i+1:]]\n ) | 4 | 0 | [] | 0 |
find-the-maximum-factor-score-of-array | Easy Approach with proper Explanation. | easy-approach-with-proper-explanation-by-7vq3 | Intuition\nWhen tackling the problem of finding the maximum factor score of an integer array after potentially removing one element, my first thought was to lev | siddhuuse | NORMAL | 2024-10-27T04:26:49.240733+00:00 | 2024-10-27T04:26:49.240764+00:00 | 392 | false | # Intuition\nWhen tackling the problem of finding the maximum factor score of an integer array after potentially removing one element, my first thought was to leverage the properties of GCD (Greatest Common Divisor) and LCM (Least Common Multiple). The factor score is defined as the product of the GCD and LCM of the array, so I realized I need to efficiently compute these values for the entire array and for each possible subset (after removing one element).\n\n# Approach\n1. I started by implementing **helper functions** to compute the GCD and LCM of two numbers. The GCD can be computed using the Euclidean algorithm, while the LCM is give by,\n``lcm(a, b) = (a * b)/gcd(a, b)``.\n\n2. I then calculated the overall GCD and LCM for the entire array. This gives me a baseline factor score.\n\n3. For each element in the array, I computed the GCD and LCM of the remaining elements (after removing the current element). I kept track of the maximum factor score found during this iteration.\n\n4. Finally, I returned the highest factor score obtained.\n\nThis method allows me to evaluate all possible configurations of the array efficiently, ensuring that I consider both cases **removing one element and keeping all elements.**\n\n# Complexity\n- **Time complexity**: The time complexity of this solution is **O(n^2)** in the worst case, where **n** is the number of elements in the input array. This is because for each of the **n** elements, we might need to compute the GCD and LCM of the remaining **n-1** elements, leading to a nested iteration.\n\n- **Space complexity**: The space complexity is **O(1)** since we are using a constant amount of space for storing variables and do not utilize any additional data structures that scale with input size.\n\n# Code\n```python\nfrom typing import List\n\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n def gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n \n def lcm(a, b):\n return (a * b) // gcd(a, b)\n \n n = len(nums)\n if n == 1:\n return nums[0] * nums[0] # Special case for a single element\n \n # Calculate overall GCD and LCM\n tot_gcd = nums[0]\n tot_lcm = nums[0]\n for num in nums[1:]:\n tot_gcd = gcd(tot_gcd, num)\n tot_lcm = lcm(tot_lcm, num)\n \n # Initial maximum score\n max_score = tot_gcd * tot_lcm\n \n # Check scores for each possible removal\n for i in range(n):\n curr_gcd = 0\n curr_lcm = 1\n for j in range(n):\n if i != j:\n curr_gcd = gcd(curr_gcd, nums[j])\n curr_lcm = lcm(curr_lcm, nums[j])\n max_score = max(max_score, curr_gcd * curr_lcm)\n \n return max_score\n | 4 | 0 | ['Math', 'Greedy', 'Python3'] | 0 |
find-the-maximum-factor-score-of-array | Easy and Fast Cpp solution | easy-and-fast-cpp-solution-by-manishbhar-ekbu | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n1.Calculate the total GCD of the entire array using a helper function.\n2 | Manishbhartiya07 | NORMAL | 2024-10-27T04:04:01.435022+00:00 | 2024-10-27T04:04:01.435043+00:00 | 1,643 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1.Calculate the total GCD of the entire array using a helper function.\n2.Calculate the total LCM of the entire array using another helper function.\n3.Compute the initial factor score using the total GCD and total LCM.\n4.Loop through each element in the array, treating each as a candidate for removal.\n5.Create a temporary array excluding the current element.\nFor the modified array (after removing the element), calculate the GCD and LCM using the helper functions.\n6.Compare it with the current maximum factor score and update.\n7.return the maximum factor score obtained.\n\n# Complexity\n- Time complexity:\nO(n2)\n\n\n- Space complexity:\nO(n)\n\n# Code\n```cpp []\n\n\nclass Solution {\npublic:\n int calculateGCD(const vector<int>& nums) {\n int gcd_val = nums[0];\n for (int i = 1; i < nums.size(); ++i) {\n gcd_val = gcd(gcd_val, nums[i]);\n }\n return gcd_val;\n }\n\n long long calculateLCM(const vector<int>& nums) {\n long long lcm_val = nums[0];\n for (int i = 1; i < nums.size(); ++i) {\n lcm_val = (lcm_val * nums[i]) / gcd(static_cast<long long>(lcm_val), static_cast<long long>(nums[i]));\n }\n return lcm_val;\n }\n\n long long maxScore(vector<int>& nums) {\n int totalGCD = calculateGCD(nums);\n long long totalLCM = calculateLCM(nums);\n\n long long maxFactorScore = 1LL * totalGCD * totalLCM;\n \n for (int i = 0; i < nums.size(); ++i) {\n vector<int> temp;\n for (int j = 0; j < nums.size(); ++j) {\n if (i != j) temp.push_back(nums[j]);\n }\n\n if (!temp.empty()) {\n int gcd = calculateGCD(temp);\n long long lcm = calculateLCM(temp);\n maxFactorScore = max(maxFactorScore, 1LL * gcd * lcm);\n }\n }\n \n return maxFactorScore;\n }\n};\n\n\n``` | 3 | 0 | ['C++'] | 1 |
find-the-maximum-factor-score-of-array | ❓What if constrains were (1 <= nums.length <= 10^5)❓ | what-if-constrains-were-1-numslength-105-tfha | \n\n### Approach\n1. Calculate Prefix and Suffix GCD/LCM Arrays:\n - We need two arrays for each of GCD and LCM:\n - prefixGCD and suffixGCD: Store the GC | Ajay_Prabhu | NORMAL | 2024-11-01T06:52:50.322994+00:00 | 2024-11-01T06:52:50.323022+00:00 | 40 | false | \n\n### Approach\n1. **Calculate Prefix and Suffix GCD/LCM Arrays**:\n - We need two arrays for each of GCD and LCM:\n - `prefixGCD` and `suffixGCD`: Store the GCD of elements from the start up to each index, and from each index to the end.\n - `prefixLCM` and `suffixLCM`: Store the LCM of elements from the start up to each index, and from each index to the end.\n \n2. **Fill Prefix and Suffix Arrays**:\n - For `prefixGCD` and `prefixLCM`, calculate GCD and LCM from left to right.\n - For `suffixGCD` and `suffixLCM`, calculate GCD and LCM from right to left.\n\n3. **Calculate Maximum Factor Score After Removing Each Element**:\n - For each element, calculate the GCD and LCM of the elements excluding the current element:\n - If removing the first element, use `suffixGCD[1]` and `suffixLCM[1]`.\n - If removing the last element, use `prefixGCD[n - 2]` and `prefixLCM[n - 2]`.\n - For elements in between, combine `prefixGCD` and `suffixGCD`, and similarly for `prefixLCM` and `suffixLCM`.\n - Compute the factor score (GCD * LCM) for each removal and track the maximum score.\n\n\n### Code\n```java\nclass Solution {\n public long maxScore(int[] nums) {\n int n = nums.length;\n if (n == 1) return (long) nums[0] * nums[0]; \n\n long[] prefixGCD = new long[n];\n long[] suffixGCD = new long[n];\n long[] prefixLCM = new long[n];\n long[] suffixLCM = new long[n];\n \n prefixGCD[0] = nums[0];\n prefixLCM[0] = nums[0];\n for (int i = 1; i < n; i++) {\n prefixGCD[i] = findGCD(prefixGCD[i - 1], nums[i]);\n prefixLCM[i] = findLCM(prefixLCM[i - 1], nums[i]);\n }\n \n suffixGCD[n - 1] = nums[n - 1];\n suffixLCM[n - 1] = nums[n - 1];\n for (int i = n - 2; i >= 0; i--) {\n suffixGCD[i] = findGCD(suffixGCD[i + 1], nums[i]);\n suffixLCM[i] = findLCM(suffixLCM[i + 1], nums[i]);\n }\n \n long maxScore = prefixGCD[n - 1] * prefixLCM[n - 1];\n for (int i = 0; i < n; i++) {\n long gcdWithoutI = (i == 0) ? suffixGCD[1] : (i == n - 1 ? prefixGCD[n - 2] : findGCD(prefixGCD[i - 1], suffixGCD[i + 1]));\n long lcmWithoutI = (i == 0) ? suffixLCM[1] : (i == n - 1 ? prefixLCM[n - 2] : findLCM(prefixLCM[i - 1], suffixLCM[i + 1]));\n \n long factorScore = gcdWithoutI * lcmWithoutI;\n maxScore = Math.max(maxScore, factorScore);\n }\n \n return maxScore;\n }\n\n public static long findGCD(long a, long b) {\n if (b == 0) return a;\n return findGCD(b, a % b);\n }\n\n public static long findLCM(long a, long b) {\n return (a / findGCD(a, b)) * b;\n }\n}\n```\n | 2 | 0 | ['Array', 'Math', 'Number Theory', 'Prefix Sum', 'Java'] | 2 |
find-the-maximum-factor-score-of-array | Easy to understand c++ soln with separate function for each task. Beats 100%. | easy-to-understand-c-soln-with-separate-zr9s7 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nCalculating lcm and gcd for nums array and then trying all possible array | Samarth1512 | NORMAL | 2024-10-27T09:31:09.835819+00:00 | 2024-10-27T09:31:09.835842+00:00 | 438 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nCalculating lcm and gcd for nums array and then trying all possible arrays by removing one element from nums and calculating product of gcd and lcm for each of them and storing the maximum of all.\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```cpp []\nclass Solution {\npublic:\nlong long gcd(long long a, long long b){\n while(a > 0 && b > 0){\n if(a > b){\n a = a % b;\n }\n else{\n b = b % a;\n }\n }\n if( a == 0)\n return b;\n return a;\n}\nlong long findlcm(vector<int> & nums){\n int n = nums.size();\n long long ans = nums[0];\n for(int i =1; i<n; i++){\n ans = (ans * 1ll * nums[i])/(gcd(ans, nums[i]));\n }\n return ans;\n}\nlong long findgcd(vector<int>& nums){\n int n = nums.size();\n long long ans = nums[0];\n for(int i = 1; i<n; i++){\n ans = gcd(ans, nums[i]);\n }\n return ans;\n}\n long long maxScore(vector<int>& nums) {\n int n = nums.size();\n long long lcm1 = findlcm(nums);\n long long gcd1 = findgcd(nums);\n long long maxi = lcm1 * 1ll * gcd1;\n long long lcm2 = 0, gcd2 = 0;\n vector<int> nums2;\n if(n > 1){\n for(int i = 0; i<n; i++){\n nums2 = nums;\n nums2.erase(nums2.begin() + i);\n lcm2 = findlcm(nums2);\n gcd2 = findgcd(nums2);\n maxi = max(maxi, lcm2 * 1ll * gcd2);\n }\n }\n return maxi;\n }\n};\n``` | 2 | 0 | ['Array', 'C++'] | 0 |
find-the-maximum-factor-score-of-array | Beat 100% , TC = O(n log(min(a, b))) , SC = O(n). | beat-100-tc-on-logmina-b-sc-on-by-expon2-m51l | 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 | expon23_9 | NORMAL | 2024-10-27T07:02:16.237043+00:00 | 2024-10-27T07:02:16.237098+00:00 | 276 | 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```cpp []\nclass Solution {\npublic:\n int hcf(vector<int>&nums)\n {\n int h = nums[0];\n for(int i =0;i<nums.size();i++)h = gcd(h,nums[i]);\n return h;\n }\n long long lcm(vector<int>nums)\n {\n long long l = nums[0];\n for(int i =0;i<nums.size();i++)l= (l*nums[i])/gcd(l,nums[i]);\n return l;\n }\n long long maxScore(vector<int>& nums) {\n long long res = hcf(nums)*lcm(nums); \n if(nums.size()==1)return (nums[0]*nums[0]);\n for(auto x : nums)\n {\n vector<int>temp = nums;\n auto it = find(temp.begin(),temp.end(),x);\n if(it!=temp.end())temp.erase(it);\n res = max(res,hcf(temp)*lcm(temp));\n }\n return res;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
find-the-maximum-factor-score-of-array | Cpp | Beats 100 % | cpp-beats-100-by-rtik-4d76 | Intuition\n Describe your first thoughts on how to solve this problem. \nGreedy\n# Approach\nCreate left and right array for gcd and lcm \n Describe your approa | rtik | NORMAL | 2024-10-27T05:47:28.734902+00:00 | 2024-10-27T05:47:28.734934+00:00 | 156 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nGreedy\n# Approach\nCreate left and right array for gcd and lcm \n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n typedef long long ll;\n ll LCM(ll a,ll b){\n ll gcd=__gcd(a,b);\n return (a/gcd)*b;\n }\n long long maxScore(vector<int>& nums) {\n int n=nums.size();\n vector<ll>left_gcd(n);\n vector<ll>right_gcd(n);\n left_gcd[0]=nums[0];\n for(int i=1;i<n;i++){\n left_gcd[i]=__gcd(left_gcd[i-1],(ll)nums[i]);\n }\n right_gcd[n-1]=nums[n-1];\n for(int i=n-2;i>=0;i--){\n right_gcd[i]=__gcd(right_gcd[i+1],(ll)nums[i]);\n }\n vector<ll>left_lcm(n);\n vector<ll>right_lcm(n);\n left_lcm[0]=nums[0];\n for(int i=1;i<n;i++){\n left_lcm[i]=LCM(left_lcm[i-1],nums[i]);\n }\n right_lcm[n-1]=nums[n-1];\n for(int i=n-2;i>=0;i--){\n right_lcm[i]=LCM(right_lcm[i+1],nums[i]);\n }\n if(n==1)return left_gcd[0]*left_lcm[0];\n ll ans=max({right_gcd[1]*right_lcm[1],left_lcm[n-2]*left_gcd[n-2]});\n for(int i=1;i<n-1;i++){\n ll gcd=__gcd(left_gcd[i-1],right_gcd[i+1]);\n ll lcm=LCM(left_lcm[i-1],right_lcm[i+1]);\n ans=max(ans,gcd*lcm);\n }\n ll res=left_lcm[n-1]*left_gcd[n-1];\n ans=max(ans,res);\n return ans;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
find-the-maximum-factor-score-of-array | Simple Easy Java Solution | simple-easy-java-solution-by-shree_govin-wja6 | Code\njava []\nclass Solution {\n private int gcd(int a, int b) {\n if (b == 0) {\n return a;\n }\n return gcd(b, a % b);\n | Shree_Govind_Jee | NORMAL | 2024-10-27T05:00:20.110709+00:00 | 2024-10-27T05:00:20.110748+00:00 | 462 | false | # Code\n```java []\nclass Solution {\n private int gcd(int a, int b) {\n if (b == 0) {\n return a;\n }\n return gcd(b, a % b);\n }\n\n private long gcd(long a, int b) {\n if (b == 0) {\n return a;\n }\n return gcd(b, (int) (a % b));\n }\n\n public long maxScore(int[] nums) {\n int n = nums.length;\n\n // edge\n if (n == 1) {\n return (long) nums[0] * nums[0];\n }\n\n int tgcd = nums[0];\n long tlcm = nums[0];\n for (int i = 1; i < nums.length; i++) {\n tgcd = gcd(tgcd, nums[i]);\n tlcm = (tlcm * nums[i]) / gcd(tlcm, nums[i]);\n }\n\n long maxScore = tgcd * tlcm;\n for (int i = 0; i < n; i++) {\n int ngcd = 0;\n long nlcm = 1;\n for (int j = 0; j < n; j++) {\n if (i != j) {\n ngcd = ngcd == 0 ? nums[j] : gcd(ngcd, nums[j]);\n nlcm = (nlcm * nums[j]) / gcd(nlcm, nums[j]);\n }\n }\n\n maxScore = Math.max(maxScore, ngcd * nlcm);\n }\n return maxScore;\n }\n}\n``` | 2 | 0 | ['Java'] | 0 |
find-the-maximum-factor-score-of-array | Beats 100% | beats-100-by-mainframekuznetsov-bbvh | Intuition\n Describe your first thoughts on how to solve this problem. \nFirst calculate the product of GCDLCM of the whole array then calculate all other possi | MainFrameKuznetSov | NORMAL | 2024-10-27T04:17:47.233150+00:00 | 2024-10-27T04:17:47.233178+00:00 | 63 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst calculate the product of GCD*LCM of the whole array then calculate all other possible products excluding 1 element per iteration.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Generate GCD*LCM of full array\n- Now iterate accross whole array.\n - Using another loop, excelude 1 element per iteration to check the new product obtained and return the maximum of all such products.\n# Complexity\n- Time complexity:- $O(n^2)$\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```cpp []\nclass Solution {\npublic:\n long long __gcd(long long a,long long b)\n {\n if(b==0)\n return a;\n return __gcd(b,a%b);\n }\n long long maxScore(vector<int>& nums) {\n if(nums.size()==1)\n return nums[0]*nums[0];\n sort(nums.begin(),nums.end());\n long long gcd=nums[0],lcm=nums[0];\n for(int i=1;i<nums.size();++i)\n {\n gcd=__gcd(gcd,(long long)nums[i]);\n lcm=(lcm*nums[i])/__gcd(lcm,(long long)nums[i]);\n }\n long long ans=gcd*lcm;\n for(int i=0;i<nums.size();++i)\n {\n long long g=-1; \n long long l=1; \n for(int j=0;j<nums.size();++j) \n { \n if(i==j) \n continue; \n if(g==-1) \n g=nums[j]; \n else \n g=__gcd(g,nums[j]);\n l=(l*nums[j])/__gcd(l,(long long)nums[j]);\n } \n long long curr=g*l; \n ans=max(ans,curr);\n }\n //cout<<a<<" "<<b<<"\\n";\n return ans;\n }\n};\n``` | 2 | 0 | ['Greedy', 'Number Theory', 'C++'] | 0 |
find-the-maximum-factor-score-of-array | Python Solution Time -- > O(N) and Space --> O(1) | python-solution-time-on-and-space-o1-by-wwzxn | IntuitionIdea to solve this problem given by Claude
Not very Hard ApproachApproach*nums is used to unpack the list as the gcd and lcm function takes only intege | Amritraj777 | NORMAL | 2025-03-27T19:43:51.809849+00:00 | 2025-03-27T19:43:51.809849+00:00 | 23 | false | # Intuition
Idea to solve this problem given by Claude
Not very Hard Approach
# Approach
***nums** is used to unpack the list as the gcd and lcm function takes only integers
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
O(N) --> Linear
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
O(1) --> Constant
# Code
```python3 []
class Solution:
def maxScore(self, nums: List[int]) -> int:
# This condition is for Edge Cases
if len(nums) == 1:
return nums[0]**2
# max_score should be default this
max_score = gcd(*nums) * lcm(*nums)
# This Loop deletes single element from list very iteration
# New Iteration new element is Deleted
# No Element left Behind
for i in range(len(nums)):
num = nums[:i] + nums[i+1:]
if num:
curr_score = gcd(*num) * lcm(*num)
max_score = max(curr_score, max_score)
return max_score
``` | 1 | 0 | ['Python3'] | 1 |
find-the-maximum-factor-score-of-array | Prefix and suffix. Simple solution O(n) | prefix-and-suffix-simple-solution-on-by-o8kxd | null | xxxxkav | NORMAL | 2025-02-11T09:46:59.408861+00:00 | 2025-02-13T15:56:10.883014+00:00 | 40 | false | ```
class Solution:
def maxScore(self, nums: List[int]) -> int:
if len(nums) == 1:
return nums[0] * nums[0]
pref_gcd = [*accumulate(nums, gcd)]
pref_lcm = [*accumulate(nums, lcm)]
suff_gcd = [*accumulate(reversed(nums), gcd)]
suff_lcm = [*accumulate(reversed(nums), lcm)]
ans = max(pref_gcd[-1] * pref_lcm[-1], pref_gcd[-2] * pref_lcm[-2], suff_gcd[-2] * suff_lcm[-2])
for i in range(1, len(nums)-1):
ans = max(ans, gcd(pref_gcd[i-1], suff_gcd[~i-1]) * lcm(pref_lcm[i-1], suff_lcm[~i-1]))
return ans
``` | 1 | 0 | ['Python3'] | 0 |
find-the-maximum-factor-score-of-array | C++ Solution | Time Complexity: O(n) | Space Complexity: O(n) | Beats 100% Runtime | c-solution-time-complexity-on-space-comp-shvf | IntuitionThe first thing that would come to your mind when thinking about removing at most one element is the need to link the elements before and after it. To | Sohil423Abuzeid | NORMAL | 2025-01-16T22:48:53.897526+00:00 | 2025-01-16T22:48:53.897526+00:00 | 74 | false | # Intuition
The first thing that would come to your mind when thinking about removing at most one element is the need to link the elements before and after it. To do that, I need to know the values of all elements after it and all elements before it, and then concatenate these values.
# Approach
<!-- Describe your approach to solving the problem. -->
The best way to achieve this is by using prefix and suffix arrays. This allows me to calculate the necessary values efficiently. I will create four arrays: two for the prefix GCD and LCM, and two for the suffix GCD and LCM. Then, for each element, I calculate the GCD between the values before and after it, and maximize the result accordingly
Take care of the following cases:
1-If the array size is one, it could cause a runtime error, so handle this case early and exit gracefully.
2-If no element is removed at all, take the full GCD and LCM of the array only once. I made the mistake of calculating it twice, so avoid that.
3-Handle edge element removing, such as removing the first or last element. I addressed these cases while initializing the ans variable.
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
we used five loops each is n so its O(n)
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
we used 4 vectors so its also O(n)
# Code
```cpp []
class Solution {
public:
long long maxScore(vector<int>& nums) {
if(nums.size()==1)return nums[0]*nums[0];
vector<long long> GcdPre(nums.size()),LcmPre(nums.size()),GcdSuf(nums.size()),LcmSuf(nums.size());
GcdPre[0]=nums[0];
LcmPre[0]=nums[0];
GcdSuf[nums.size()-1]=nums[nums.size()-1];
LcmSuf[nums.size()-1]=nums[nums.size()-1];
for(int i = 1 ; i <nums.size();i++)
{
GcdPre[i]=__gcd(GcdPre[i-1],nums[i]*1ll);
}
for(int i = 1 ; i <nums.size();i++)
{
LcmPre[i]=(LcmPre[i-1]*nums[i]*1ll)/__gcd(LcmPre[i-1],nums[i]*1ll);
}
for(int i = nums.size()-2 ; i >=0;i--)
{
GcdSuf[i]=__gcd(GcdSuf[i+1],nums[i]*1ll);
}
for(int i = nums.size()-2 ; i >=0;i--)
{
LcmSuf[i]=(LcmSuf[i+1]*nums[i]*1ll)/__gcd(LcmSuf[i+1],nums[i]*1ll);
}
long long ans = max({GcdPre[nums.size()-1]*LcmPre[nums.size()-1],GcdSuf[0]*LcmSuf[0],GcdPre[nums.size()-2]*LcmPre[nums.size()-2],GcdSuf[1]*LcmSuf[1]});
for(int i =1 ; i < nums.size()-1;i++)
{
ans = max(ans,__gcd(GcdPre[i-1],GcdSuf[i+1])*((LcmSuf[i+1])/__gcd(LcmSuf[i+1],LcmPre[i-1])*LcmPre[i-1]));
}
return ans ;
}
};
``` | 1 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | [C++] No trick, just simple implementation | c-no-trick-just-simple-implementation-by-0egh | lcm of an array: we iterate throguh the array and calculate for each position the new lcm, lcm at i will be lcm[i] = lcm(lcm_nums[i-1], nums[i]), since for posi | bora_marian | NORMAL | 2024-11-02T07:59:29.650173+00:00 | 2024-11-02T08:56:19.398223+00:00 | 91 | false | lcm of an array: we iterate throguh the array and calculate for each position the new lcm, lcm at i will be ```lcm[i] = lcm(lcm_nums[i-1], nums[i])```, since for position i we need only the lcm at ```i-1``` we can keep it in a single variable ```lcm_nums = lcm(lcm_nums, nums[i]);```\ngcf of an array: the same as for LCM, we iterate throguh the array and calculate for each position the new gcd, gcd at i will be ```gcd[i] = gcd(gcd_nums[i-1], nums[i])```, since for position i we need only the gcd at ```i-1``` we can keep it in a single variable ```gcd_nums = gcd(gcd_nums, nums[i]);```\nCalcualte lcm and gcd by eliminating 1 index from nums.We start from -1 simulating that we don\'t eliminated any number from nums.\n# Code\n```cpp []\nclass Solution {\npublic:\n long long maxScore(vector<int>& nums) {\n long long result = -1, gcd_nums = -1, lcm_nums = -1;\n int n = nums.size();\n for (int k = -1; k < n; k++) {\n gcd_nums = -1, lcm_nums = -1;\n for (int i = 0; i < n; i++) {\n if (i == k) continue;\n if (lcm_nums < 0) {\n lcm_nums = nums[i], gcd_nums = nums[i];\n continue;\n }\n gcd_nums = gcd(gcd_nums, nums[i]);\n lcm_nums = lcm(lcm_nums, nums[i]);\n }\n result = max(result, gcd_nums * lcm_nums);\n }\n return result;\n }\n long long gcd(long long a, long long b) {\n while(a > 0 && b > 0) {\n if (a > b) \n a = a % b;\n else \n b = b % a;\n }\n return a != 0 ? a : b;\n }\n long long lcm(long long a, long long b) {\n long long ab_gcd = gcd(a, b);\n return (a / ab_gcd) * b;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | Good and Easy to understand solution using prefix and suffix gcd and lcm arrays | good-and-easy-to-understand-solution-usi-535e | 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 | Ronitwanare | NORMAL | 2024-10-29T07:36:57.825907+00:00 | 2024-10-29T07:38:00.271451+00:00 | 17 | 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```cpp []\nclass Solution {\npublic:\n long long gcd(long long a, long long b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n\n long long lcm(long long a, long long b) {\n return (a / gcd(a, b)) * b; \n }\n\n long long maxScore(vector<int>& nums) {\n // step 1. make gcd prefix suffix\n // step 2. make lcm prefix suffix \n // step 3. loop in element and find max score excluding that element\n int n = nums.size();\n if (n == 1) return (long long)nums[0] * nums[0]; \n\n vector<int> gcdp(n), gcds(n);\n vector<long long> lcmp(n), lcms(n);\n\n // Prefix GCD\n gcdp[0] = nums[0];\n for (int i = 1; i < n; i++) {\n gcdp[i] = gcd(gcdp[i - 1], nums[i]);\n }\n\n // Suffix GCD\n gcds[n - 1] = nums[n - 1];\n for (int i = n - 2; i >= 0; i--) {\n gcds[i] = gcd(gcds[i + 1], nums[i]);\n }\n\n // Prefix LCM\n lcmp[0] = nums[0];\n for (int i = 1; i < n; i++) {\n lcmp[i] = lcm(lcmp[i - 1], nums[i]);\n }\n\n // Suffix LCM\n lcms[n - 1] = nums[n - 1];\n for (int i = n - 2; i >= 0; i--) {\n lcms[i] = lcm(lcms[i + 1], nums[i]);\n }\n\n long long res = lcmp[n - 1] * gcdp[n - 1]; // Initial max score\n\n // Loop to find max score by excluding each element\n for (int i = 0; i < n; i++) {\n int remgcd;\n long long remlcm;\n\n if (i == 0) {\n remgcd = gcds[1];\n remlcm = lcms[1];\n } else if (i == n - 1) {\n remgcd = gcdp[n - 2];\n remlcm = lcmp[n - 2];\n } else {\n remgcd = gcd(gcdp[i - 1], gcds[i + 1]);\n remlcm = lcm(lcmp[i - 1], lcms[i + 1]);\n }\n\n res = max(res, remgcd * remlcm);\n }\n\n return res;\n }\n};\n\n``` | 1 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | Simple Python solution | Beats 100% in time and memory | simple-python-solution-beats-100-in-time-ec5e | Intuition\nThe GCD of multiple numbers can be computed by taking the GCD of the first two, then repeating with the next number:\n\nGCD(a, b, c, ...) = GCD(GCD(a | david1121 | NORMAL | 2024-10-28T04:22:26.332587+00:00 | 2024-10-28T04:22:26.332614+00:00 | 64 | false | # Intuition\nThe GCD of multiple numbers can be computed by taking the GCD of the first two, then repeating with the next number:\n\n$$GCD(a, b, c, ...) = GCD(GCD(a, b), c, ...)$$\n\nThe same thing is true for the LCM:\n\n$$LCM(a, b, c, ...) = LCM(LCM(a, b), c, ...)$$\n\nTo get the LCM of two numbers, we can multiply them and divide by their GCD.\nTo get the GCD of two numbers, we can use the [Eucledian algorithm](https://en.wikipedia.org/wiki/Euclidean_algorithm).\n\n\n# Approach\nRemove each number in the array, and compute the resulting score each time. Store the max score in a variable. Also compute the score of the array without removing numbers.\n\n# Code\n```python3 []\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n if len(nums) == 1: return nums[0] ** 2\n\n def gcd_all(nums):\n def gcd(a, b):\n if a is None or b is None:\n # This handles the None that replaces a removed number\n return a or b\n if b == 0:\n return a\n return gcd(b, a % b)\n return reduce(gcd, nums)\n\n def lcm_all(nums):\n def lcm(a, b):\n if a is None or b is None:\n # This handles the None that replaces a removed number\n return a or b\n return (a * b) // gcd(a, b)\n return reduce(lcm, nums)\n\n def get_score(nums):\n return gcd_all(nums) * lcm_all(nums)\n\n nums.append(None) # To test the whole array without removing any numbers\n max_score = 0\n for i in range(len(nums)):\n # Remove current number\n temp = nums[i]\n nums[i] = None\n\n max_score = max(max_score, get_score(nums))\n\n # Put it back\n nums[i] = temp\n\n return max_score\n\n```\n\n# Test cases\n```\n[2,4,8,16]\n[1,2,3,4,5]\n[3]\n[10,18,16]\n[15,30]\n[1,13,28]\n[17,25,20,30,11,13]\n``` | 1 | 0 | ['Python3'] | 0 |
find-the-maximum-factor-score-of-array | Greedy with prefix array | 4 ms - beats 100.00% | greedy-with-prefix-array-4-ms-beats-1000-018g | Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n\n# Co | tigprog | NORMAL | 2024-10-27T13:43:16.024116+00:00 | 2024-10-27T13:43:40.178596+00:00 | 33 | false | # Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nfrom math import lcm, gcd\n\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n suffixes = []\n l, g = 1, 0\n for elem in reversed(nums):\n suffixes.append((l, g))\n l = lcm(l, elem)\n g = gcd(g, elem)\n \n result = l * g\n l, g = 1, 0\n\n for i, elem in enumerate(nums):\n prefix_l, prefix_g = suffixes.pop()\n result = max(\n result,\n lcm(l, prefix_l) * gcd(g, prefix_g),\n )\n l = lcm(l, elem)\n g = gcd(g, elem)\n \n return result\n``` | 1 | 0 | ['Greedy', 'Suffix Array', 'Python3'] | 0 |
find-the-maximum-factor-score-of-array | python3 bruteforce | python3-bruteforce-by-0icy-1q1m | \n\n# Code\npython3 []\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n if len(nums) == 1:\n return nums[0]**2\n ans | 0icy | NORMAL | 2024-10-27T06:34:01.829295+00:00 | 2024-10-27T06:34:01.829318+00:00 | 23 | false | \n\n# Code\n```python3 []\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n if len(nums) == 1:\n return nums[0]**2\n ans = reduce(lcm,nums)*reduce(gcd,nums)\n for i in range(len(nums)):\n temp = nums[:i]+nums[i+1:]\n ans = max(ans,reduce(lcm,temp)*reduce(gcd,temp))\n return ans\n``` | 1 | 0 | ['Python3'] | 0 |
find-the-maximum-factor-score-of-array | Beats 100% || Constant Space | beats-100-constant-space-by-amar_1-w4jr | Complexity\n- Time complexity:\nO(n^2)\n- Space complexity:\nO(1)\n\n# Code\njava []\nclass Solution {\n public long gcd(long m, long n){\n while(n != | Amar_1 | NORMAL | 2024-10-27T05:35:53.354696+00:00 | 2024-10-27T05:35:53.354722+00:00 | 37 | false | # Complexity\n- Time complexity:\nO(n^2)\n- Space complexity:\nO(1)\n\n# Code\n```java []\nclass Solution {\n public long gcd(long m, long n){\n while(n != 0){\n long gcd = m % n;\n m = n;\n n = gcd;\n }\n\n return m;\n }\n public long lcm(long m, long n){\n if (m == 0 || n == 0) return 0;\n return ((m * n)/gcd(m, n));\n }\n public long maxScore(int[] nums) {\n if(nums.length == 0) return 0; \n if(nums.length == 1) return nums[0]*nums[0];\n\n long findLcm = nums[0], findGcd = nums[0];\n\n //without removing\n for(int i = 1; i < nums.length; i++){\n findLcm = lcm(findLcm, nums[i]);\n findGcd = gcd(findGcd, nums[i]);\n }\n long withoutRemoving = findLcm * findGcd;\n\n long maxWithRemoving = 0;\n for(int i = 0; i < nums.length; i++){\n long solveLcm = -1, solveGcd = -1;\n for(int j = 0; j < nums.length; j++){\n if(i == j) continue;\n\n if(solveLcm == -1){\n solveLcm = nums[j];\n solveGcd = nums[j];\n }\n else{\n solveLcm = lcm(solveLcm, nums[j]);\n solveGcd = gcd(solveGcd, nums[j]);\n }\n }\n\n long withRemoving = solveLcm * solveGcd;\n maxWithRemoving = Math.max(withRemoving, maxWithRemoving);\n }\n\n return Math.max(withoutRemoving, maxWithRemoving);\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
find-the-maximum-factor-score-of-array | Beats 100% in both Time and Space || Simplest Approach to understand | beats-100-in-both-time-and-space-simples-1k7c | Complexity\n- Time complexity:\n \uD835\uDC42(n^2)\n\n- Space complexity:\n O(n)\n\n\n# Code\njava []\nclass Solution {\n public long maxScore(int[] nu | Shivam_Mainro | NORMAL | 2024-10-27T05:08:38.168702+00:00 | 2024-10-27T05:08:38.168744+00:00 | 34 | false | # Complexity\n- Time complexity:\n \uD835\uDC42(n^2)\n\n- Space complexity:\n O(n)\n\n\n# Code\n```java []\nclass Solution {\n public long maxScore(int[] nums) {\n int n = nums.length;\n if(n==0) return 0;\n if(n==1) return (long)(nums[0] * nums[0]);\n long maxans = lcmarr(nums) * gcdarr(nums);\n for(int i =0 ; i<n; i++){\n int[] newarr = new int[n-1];\n int k =0;\n for(int j =0 ; j<n;j++){\n if(i == j) continue;\n newarr[k] = nums[j];\n k++;\n }\n long maxbyremove = lcmarr(newarr) * gcdarr(newarr);\n maxans = Math.max(maxans, maxbyremove);\n }\n return maxans;\n }\n\n public long gcd(long a, long b){\n while(b!=0){\n long c = a%b;\n a=b;\n b=c;\n }\n return a;\n }\n public long lcm(long a, long b){\n return (a*b)/gcd(a,b);\n }\n public long gcdarr(int[] arr){\n long ans = arr[0];\n for(int i =1;i<arr.length;i++){\n ans = gcd(ans, arr[i]);\n }\n return ans;\n }\n\n public long lcmarr(int[] arr){\n long ans = arr[0];\n for(int i =1; i<arr.length;i++){\n ans = lcm(ans, arr[i]);\n }\n return ans;\n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
find-the-maximum-factor-score-of-array | radhe radhe || simple and easy solution || beats 100% | radhe-radhe-simple-and-easy-solution-bea-96d2 | 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 | neerajofficial1919 | NORMAL | 2024-10-27T04:40:57.638771+00:00 | 2024-10-27T04:40:57.638798+00:00 | 191 | 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```cpp []\nclass Solution {\npublic:\n int gcd(long long a,long long b){\n if(!b)return a;\n return gcd(b,a%b);\n }\n long long solve(multiset<long long> &st){\n long long a1=-1,a2=-1;\n for(auto &&val:st){\n if(a1==-1)a1=val,a2=val;\n else{\n a1=gcd(a1,val);\n a2=(a2*val)/gcd(a2,val);\n }\n }\n return a1*a2;\n }\n long long maxScore(vector<int>& nums) {\n multiset<long long> st(nums.begin(),nums.end());\n long long ans=solve(st);\n for(auto &&val:nums){\n st.erase(st.find(val));\n ans=max(ans,solve(st));\n st.insert(val);\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | O(n^2) solution 7 line AC code (bruteforce) | on2-solution-7-line-ac-code-bruteforce-b-bsf5 | Intuition\nYes gcd and lcm pre-exist for array in python as well which i don\'t know during contest.\n# Approach\nyes this is an easy code with self explainatio | Divyanshu52Singhal | NORMAL | 2024-10-27T04:16:01.850012+00:00 | 2024-10-27T04:16:01.850037+00:00 | 146 | false | # Intuition\nYes gcd and lcm pre-exist for array in python as well which i don\'t know during contest.\n# Approach\nyes this is an easy code with self explaination \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```python3 []\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n ans=gcd(*nums)*lcm(*nums) #whole array\n for i in range(len(nums)):\n temp=(nums[:i]+nums[i+1:]) #skipping ith index\n g=gcd(*temp)\n l=lcm(*temp)\n ans=max(ans,l*g)\n return ans\n``` | 1 | 0 | ['Python3'] | 2 |
find-the-maximum-factor-score-of-array | This Solution You Will never Forget | | C++ | this-solution-you-will-never-forget-c-by-c33b | 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 | Ninja_1006 | NORMAL | 2024-10-27T04:06:20.079518+00:00 | 2024-10-27T04:06:20.079546+00:00 | 197 | 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```cpp []\nclass Solution {\npublic:\n long long gcd(long long a, long long b)\n {\n return (b==0) ? a : gcd(b,a%b);\n }\n\n long long findlcm(vector<int> &arr, int n)\n {\n long long lcm =arr[0];\n for (int i = 1; i < n; i++){\n lcm = (((arr[i] * lcm)) / (gcd(arr[i], lcm)));\n }\n return lcm;\n }\n long long findGCD(vector<int> &arr, int n)\n {\n long long result = arr[0];\n for (int i = 1; i < n; i++)\n {\n result = gcd(arr[i], result);\n if(result == 1) return 1;\n }\n return result;\n }\n long long maxScore(vector<int>& nums) {\n if(nums.size()==1) return (1ll)*nums[0]*nums[0];\n long long lcm = findlcm(nums,nums.size());\n long long gcd1 = findGCD(nums,nums.size());\n long long ans=(long long)lcm*gcd1;\n for(int i=0;i<nums.size();i++){\n vector<int> temp(nums.begin(),nums.end());\n temp.erase(temp.begin()+i);\n long long lcm2 = findlcm(temp,temp.size());\n long long gcd2 = findGCD(temp,temp.size());\n ans = max(ans,((long long)lcm2*gcd2));\n }\n return ans;\n }\n};\n``` | 1 | 1 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | Easiest Solution 💡 | easiest-solution-by-sobhandevp2021-y66z | 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 | sobhandevp2021 | NORMAL | 2024-10-27T04:05:02.556518+00:00 | 2024-10-27T04:05:02.556538+00:00 | 239 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n private long gcd(long a, long b) {\n return b == 0 ? a : gcd(b, a % b);\n }\n\n private long gcdOfArray(int[] arr) {\n long result = arr[0];\n for (int num : arr) {\n result = gcd(result, (long)num);\n }\n return result;\n }\n\n private long lcm(long a, long b) {\n return (a * b) / gcd(a, b);\n }\n\n private long lcmOfArray(int[] arr) {\n long result = arr[0];\n for (int num : arr) {\n result = lcm(result, (long)num);\n }\n return result;\n }\n\n \n public long maxScore(int[] nums) {\n int n = nums.length;\n if (n == 1) {\n return (long) nums[0] * nums[0];\n }\n\n long totalGCD = gcdOfArray(nums);\n long totalLCM = lcmOfArray(nums);\n long maxScore = totalGCD * totalLCM;\n\n for (int i = 0; i < n; i++) {\n int[] tempArray = new int[n - 1];\n int index = 0;\n for (int j = 0; j < n; j++) {\n if (j != i) {\n tempArray[index++] = nums[j];\n }\n }\n\n long currentGCD = gcdOfArray(tempArray);\n long currentLCM = lcmOfArray(tempArray);\n long currentScore =currentGCD * currentLCM;\n\n maxScore = Math.max(maxScore, currentScore);\n }\n\n return maxScore;\n }\n}\n\n``` | 1 | 0 | ['Math', 'Java'] | 1 |
find-the-maximum-factor-score-of-array | easy way to solve | easy-way-to-solve-by-kamesh-babu-qy3k | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Kamesh-Babu | NORMAL | 2025-03-06T15:46:22.892179+00:00 | 2025-03-06T15:46:22.892179+00:00 | 4 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
public:
long long lcm(long long a, long long b) {
return (a / std::gcd(a, b)) * b;
}
long long lcmArray(const std::vector<int>& nums) {
if (nums.empty()) return 1;
long long result = nums[0];
for (int i = 1; i < nums.size(); ++i) {
result = lcm(result, nums[i]);
}
return result;
}
long long maxScore(std::vector<int>& nums) {
int n = nums.size();
if (n == 1) {
return static_cast<long long>(nums[0]) * nums[0];
}
int fullGCD = nums[0];
long long fullLCM = lcmArray(nums);
for (int i = 1; i < n; ++i) {
fullGCD = std::gcd(fullGCD, nums[i]);
}
long long maxFactorScore = static_cast<long long>(fullGCD) * fullLCM;
for (int i = 0; i < n; ++i) {
int currentGCD = 0;
vector<int> remainingElements;
for (int j = 0; j < n; ++j) {
if (j != i) {
remainingElements.push_back(nums[j]);
currentGCD = currentGCD == 0 ? nums[j] : std::gcd(currentGCD, nums[j]);
}
}
long long currentLCM = lcmArray(remainingElements);
long long factorScore = static_cast<long long>(currentGCD) * currentLCM;
maxFactorScore = std::max(maxFactorScore, factorScore);
}
return maxFactorScore;
}
};
``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | Easy solution | easy-solution-by-koushik_55_koushik-80ro | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Koushik_55_Koushik | NORMAL | 2025-02-09T16:47:19.208977+00:00 | 2025-02-09T16:47:19.208977+00:00 | 4 | 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 []
import math
from functools import *
class Solution:
def maxScore(self, nums: List[int]) -> int:
def gcdd(*nums):
return reduce(math.gcd,nums)
def lcmm(*nums):
return reduce(math.lcm,nums)
n=len(nums)
k=gcdd(*nums)
k1=lcmm(*nums)
max_score = k * k1
for i in range(n):
f = nums[:i] + nums[i+1:]
if f:
max_score = max(max_score, gcdd(*f) * lcmm(*f))
return max_score
``` | 0 | 0 | ['Python3'] | 0 |
find-the-maximum-factor-score-of-array | Brute-forcing solution by slicing and calculating LCM and GCD for remaining elements | brute-forcing-solution-by-slicing-and-ca-ur2x | IntuitionWe'll approach this problem in a rather brute-"forcish" fashion. We'll ignore the element at each position in nums and calculate the LCM and GCD for th | mnjk | NORMAL | 2025-02-08T14:08:30.854380+00:00 | 2025-02-08T14:08:30.854380+00:00 | 3 | false | # Intuition
We'll approach this problem in a rather brute-"forcish" fashion. We'll ignore the element at each position in `nums` and calculate the LCM and GCD for the remaining elements while keeping track of the maximum value.
# Approach
The LCM and GCD of a single number are the number itself:
```py
if L == 1:
return nums[0]**2
```
The factor score of an empty array is 0:
```py
if L == 0:
return 0
```
The GCD is associative, therefore `GCD(x, y, z)` is the same as:
```
GCD(GCD(x, y), z)
```
Therefore, we can simply use `reduce()` to process all the elements and use the built-in `lcm()` and `gcd()` as our *reducer function*:
```py
def _lcm(xs):
return reduce(lambda x, y: x * y // gcd(x, y), xs)
def _gcd(xs):
return reduce(gcd, xs)
```
We'll step over each position of the array and slice of the prefix and suffix at our current index `i` without the element at `i`:
```py
slc = nums[:i] + nums[i + 1:]
```
We then pass this slice to our `_lcm()` and `_gcm()` and keep track of the maximum value.
Since we're allowed to remove **at most** one element, so we may get the maximum factor score by not removing an element from the array at all, therefore we'll initialize our *factor score result* with the score that we obtain we considering all the elements in `nums`:
```py
fcx = _lcm(nums) * _gcd(nums)
```
# Complexity
- Time complexity: $$O(n^2)$$
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: $$O(n)$$
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class Solution:
def maxScore(self, nums: List[int]) -> int:
L = len(nums)
if L == 0:
return 0
if L == 1:
return nums[0]**2
def _lcm(xs):
return reduce(lambda x, y: x * y // gcd(x, y), xs)
def _gcd(xs):
return reduce(gcd, xs)
fcx = _lcm(nums) * _gcd(nums)
for i in range(L):
slc = nums[:i] + nums[i + 1:]
x = _lcm(slc)
y = _gcd(slc)
fcx = max(fcx, x * y)
return fcx
``` | 0 | 0 | ['Number Theory', 'Python3'] | 0 |
find-the-maximum-factor-score-of-array | GCD,LCM RELATION WITH RESOURCES (EASY LOGIC EXPLAINATION) | gcdlcm-relation-with-resources-easy-logi-iuh7 | IntuitionApproachComplexity
Time complexity:
Space complexity:
Code | Prahlad_07 | NORMAL | 2025-02-03T08:39:19.030373+00:00 | 2025-02-03T08:39:19.030373+00:00 | 4 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```cpp []
class Solution {
private:
long long GCD(long long a, long long b) {
return b ? GCD(b, a % b) : a;
}
long long LCM(long long a, long long b) {
return (a / GCD(a, b)) * b;
}
long long findGCD(vector<int>& nums) {
long long res = nums[0];
for (int i = 1; i < nums.size(); i++) res = GCD(res, nums[i]);
return res;
}
long long findLCM(vector<int>& nums) {
long long res = nums[0];
for (int i = 1; i < nums.size(); i++) res = LCM(res, nums[i]);
return res;
}
public:
long long maxScore(vector<int>& nums) {
long long ans=findLCM(nums)*findGCD(nums);
int n=nums.size();
if(n==1){
return nums[0]*nums[0];
}
for(int i=0;i<n;i++){
vector<int>temp;
for(int j=0;j<n;j++){
if(j!=i){
temp.push_back(nums[j]);
}
}
ans=max(ans,findLCM(temp)*findGCD(temp));
}
return ans;
//-->note-->agar or bhi jyada effcient optimization chaiye then use multiset ,so you would be able to maintain the insertion and deletion in less time;
// resources used -->https://cp-algorithms.com/algebra/euclid-algorithm.html
}
};
``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | C++ || Prefix & Suffix || Beats 100% || Easy to Understand | c-prefix-suffix-beats-100-easy-to-unders-upqi | Complexity
Time complexity: O(n⋅log(max_value)) (max_value here 30)
Space complexity: O(n)
Code | james_thorn | NORMAL | 2024-12-16T21:44:22.063649+00:00 | 2024-12-16T21:44:22.063649+00:00 | 7 | false | # Complexity\n- Time complexity: O(n\u22C5log(max_value)) (max_value here 30)\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 []\n#define ll long long\nclass Solution {\npublic:\n long long gcd(ll div, ll qo)\n {\n while(qo != 0)\n {\n ll rem = div % qo;\n div = qo;\n qo = rem;\n }\n return div;\n }\n\n long long lcm(ll a, ll b) {\n return (a / gcd(a, b)) * b;\n }\n\n long long maxScore(vector<int>& v) {\n if(v.empty()) return 0;\n int n = v.size();\n if(n==1) return v[0]*v[0];\n\n vector<ll> preGCD(n,v[0]), preLCM(n,v[0]), sufGCD(n,v[n-1]), sufLCM(n,v[n-1]);\n\n for(int i=1; i<n; i++)\n {\n preGCD[i] = gcd(preGCD[i-1],v[i]);\n preLCM[i] = lcm(preLCM[i-1],v[i]);\n }\n\n for(int i=n-2; i>=0; i--)\n {\n sufGCD[i] = gcd(sufGCD[i+1],v[i]);\n sufLCM[i] = lcm(sufLCM[i+1],v[i]);\n }\n\n long long ans = preGCD[n-1] * preLCM[n-1];\n ans = max({ans,preGCD[n-2] * preLCM[n-2], sufGCD[1] * sufLCM[1]});\n\n for(int i=1; i<n-1; i++)\n {\n ll a = lcm(preLCM[i-1],sufLCM[i+1]);\n ll b = gcd(preGCD[i-1],sufGCD[i+1]);\n\n ans = max(ans, a*b);\n }\n\n return ans;\n\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | Python Brute Force | python-brute-force-by-kaluginpeter-up2e | \n\n# Complexity\n- Time complexity: O(N**2)\n\n- Space complexity: O(N)\n\n# Code\npython3 []\ndef gcd(a, b):\n return math.gcd(a, b)\n\ndef lcm(a, b):\n | kaluginpeter | NORMAL | 2024-11-26T17:12:27.810464+00:00 | 2024-11-26T17:12:27.810501+00:00 | 5 | false | \n\n# Complexity\n- Time complexity: O(N**2)\n\n- Space complexity: O(N)\n\n# Code\n```python3 []\ndef gcd(a, b):\n return math.gcd(a, b)\n\ndef lcm(a, b):\n return abs(a * b) // gcd(a, b)\n\ndef gcd_of_list(numbers):\n return reduce(gcd, numbers)\n\ndef lcm_of_list(numbers):\n return reduce(lcm, numbers)\n\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n if len(nums) == 1:\n return nums[0] * nums[0]\n max_output: int = gcd_of_list(nums) * lcm_of_list(nums)\n for idx in range(len(nums)):\n second = nums[:idx] + nums[idx + 1:]\n max_output = max(max_output, gcd_of_list(second) * lcm_of_list(second))\n return max_output\n``` | 0 | 0 | ['Array', 'Math', 'Number Theory', 'Python3'] | 0 |
find-the-maximum-factor-score-of-array | Using gcd and lcm concept | using-gcd-and-lcm-concept-by-risabhuchih-dbwj | \njava []\nclass Solution {\n public long maxScore(int[] nums) {\n if(nums.length==1)return nums[0]*nums[0];\n long ans=f(-1,nums);\n for | risabhuchiha | NORMAL | 2024-11-25T07:50:12.640144+00:00 | 2024-11-25T07:50:12.640184+00:00 | 9 | false | \n```java []\nclass Solution {\n public long maxScore(int[] nums) {\n if(nums.length==1)return nums[0]*nums[0];\n long ans=f(-1,nums);\n for(int i=0;i<nums.length;i++){\n ans=Math.max(f(i,nums),ans);\n } \n return ans;\n }\n public long f(int idx,int[] nums){\n long g,l;\n if(idx==0){\n g=nums[1];\n l=nums[1];\n }\n else{\n g=nums[0];\n l=nums[0]; \n }\n for(int i=1;i<nums.length;i++){\n if(idx==i)continue;\n g=gcd(nums[i],g);\n l=lcm(nums[i],l);\n }\n return g*l;\n }\n public long gcd(long a,long b){\n if(b==0)return a;\n return gcd(b,a%b);\n }\n public long lcm(long a,long b){\n return (a*b)/gcd(a,b);\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-the-maximum-factor-score-of-array | Simple and Easy JAVA Solution , Brute Force approach | simple-and-easy-java-solution-brute-forc-v4qd | 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 | Triyaambak | NORMAL | 2024-11-09T07:42:16.958793+00:00 | 2024-11-09T07:42:16.958829+00:00 | 7 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public long maxScore(int[] nums) {\n if(nums.length == 0)\n return 0;\n if(nums.length == 1)\n return nums[0] * nums[0];\n\n long max = findAns(nums,-1);\n\n for(int i=0;i<nums.length;i++)\n max = Math.max(max , findAns(nums,i));\n \n return max;\n }\n\n private static long findAns(int nums[],int ind){\n long gcd = ind == 0 ? nums[1] : nums[0];\n long lcm = gcd;\n for(int i= (ind == 0 ? 2 : 1);i<nums.length;i++){\n if(i != ind){\n gcd = gcd(gcd,(long)nums[i]);\n lcm = (lcm * nums[i]) / gcd(lcm ,(long)nums[i]);\n }\n }\n\n return gcd * lcm;\n }\n\n private static long gcd(long a, long b){\n while (b != 0) {\n long rem = a % b;\n a = b;\n b = rem;\n }\n return a;\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-the-maximum-factor-score-of-array | Two liner || most DISGUSTING code you'll ever see | two-liner-most-disgusting-code-youll-eve-j3ea | Code\npython3 []\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n r = [[[n % q**i for i in range(1,5)].count(0) for q in (2,3,5,7,11,1 | dingotron | NORMAL | 2024-11-07T17:10:34.437407+00:00 | 2024-11-07T17:10:34.437441+00:00 | 13 | false | # Code\n```python3 []\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n r = [[[n % q**i for i in range(1,5)].count(0) for q in (2,3,5,7,11,13,17,19,23,29)] for n in range(31)] \n return nums[0]** 2 if len(nums) == 1 else max((f := lambda l: prod((2,3,5,7,11,13,17,19,23,29)[i]**(min(s := [r[n][i] for n in l])+max(s)) for i in range(10)))(nums), max(f(c) for c in combinations(nums, len(nums)-1))) \n```\n# Notes\n<!-- Describe your first thoughts on how to solve this problem. -->\nTry submitting for yourself! Quite slow though\n\nJust for fun squeezed it into 2 lines - lots of disgusting use of lambda func, defining variables midline, if else midline...\n\nCant be bothered to explain but essentially stored each value of nums as its prime factor representation in r... then used the fact that gcd takes the min of prime powers of each element while lcm takes the max... and loop through combinations with one element removed.\n\nDone without both gcd and lcm functions from math module... stupid me didnt know there were already functions for them... \n\n\n \n | 0 | 0 | ['Python3'] | 0 |
find-the-maximum-factor-score-of-array | java simple solution | java-simple-solution-by-trivedi_cs1-pi9j | 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 | trivedi_cs1 | NORMAL | 2024-11-07T11:45:16.753741+00:00 | 2024-11-07T11:45:16.753762+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public long gcd(long a,long b)\n {\n while(a%b!=0)\n {\n long t=a%b;\n a=b;\n b=t;\n }\n return b;\n }\n public long maxScore(int[] nums) {\n int n=nums.length;\n if(n==1)\n {\n return nums[0]*nums[0];\n }\n int idx=0;\n long ans=0;\n while(idx<=n)\n {\n List<Integer>al=new ArrayList<>();\n for(int i=0;i<n;i++)\n {\n if(idx!=i)\n {\n al.add(nums[i]);\n }\n }\n if(al.size()==1)\n {\n ans=Math.max(ans,al.get(0)*al.get(0));\n idx++;\n continue;\n }\n idx++;\n long currentGCD = gcd(al.get(0), al.get(1));\n long currentLCM = (al.get(0) * al.get(1)) / currentGCD;\n\n for (int i = 2; i < al.size(); i++) {\n currentGCD = gcd(currentGCD, al.get(i));\n currentLCM = (currentLCM / gcd(currentLCM, al.get(i))) * al.get(i); // Safe LCM calculation\n }\n\n ans = Math.max(ans, (long) (currentGCD * currentLCM));\n }\n return ans;\n \n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-the-maximum-factor-score-of-array | [C] prefix & suffix | Time: O(n), Space: O(n) | c-prefix-suffix-time-on-space-on-by-zhan-qmkz | C []\nstatic int gcd(int a, int b){\n\twhile (b != 0){\n\t\tconst int c = a % b;\n\n\t\ta = b;\n\t\tb = c;\n\t}\n\n\treturn a;\n}\n\nstatic int64_t gcd_int64(in | zhang_jiabo | NORMAL | 2024-11-07T07:50:14.548409+00:00 | 2024-11-07T08:24:53.573322+00:00 | 12 | false | ```C []\nstatic int gcd(int a, int b){\n\twhile (b != 0){\n\t\tconst int c = a % b;\n\n\t\ta = b;\n\t\tb = c;\n\t}\n\n\treturn a;\n}\n\nstatic int64_t gcd_int64(int64_t a, int64_t b){\n\twhile (b != 0){\n\t\tconst int64_t c = a % b;\n\n\t\ta = b;\n\t\tb = c;\n\t}\n\n\treturn a;\n}\nstatic int64_t lcm_int64(const int64_t a, const int64_t b){\n\treturn a / gcd_int64(a, b) * b;\n}\n\nint64_t maxScore(const int * const nums, const int numsLen){\n\tif (0 == numsLen){\n\t\treturn 0;\n\t}\n\tassert(numsLen >= 1);\n\n\ttypedef struct LcmGcd{\n\t\tint64_t lcm;\n\t\tint gcd;\n\t} LcmGcd;\n\n\tLcmGcd prefixs[numsLen];\n\tprefixs[0].lcm = 1;\n\tprefixs[0].gcd = 0;\n\tfor (int i = 1; i < numsLen; i += 1){\n\t\tprefixs[i].lcm = lcm_int64(prefixs[i - 1].lcm, nums[i - 1]);\n\t\tprefixs[i].gcd = gcd(prefixs[i - 1].gcd, nums[i - 1]);\n\t}\n\n\tLcmGcd suffixs[numsLen];\n\tsuffixs[numsLen - 1].lcm = 1;\n\tsuffixs[numsLen - 1].gcd = 0;\n\tfor (int i = numsLen - 2; i >= 0; i -= 1){\n\t\tsuffixs[i].lcm = lcm_int64(suffixs[i + 1].lcm, nums[i + 1]);\n\t\tsuffixs[i].gcd = gcd(suffixs[i + 1].gcd, nums[i + 1]);\n\t}\n\n\tint64_t maxFactorScore = lcm_int64(prefixs[numsLen - 1].lcm, nums[numsLen - 1]) *\n\t\tgcd(prefixs[numsLen - 1].gcd, nums[numsLen - 1]); //remove nothing\n\tfor (int i = 0; i < numsLen; i += 1){\n\t\tconst int64_t curFactorScore = lcm_int64(prefixs[i].lcm, suffixs[i].lcm) *\n\t\t\tgcd(prefixs[i].gcd, suffixs[i].gcd);\n\t\tif (curFactorScore > maxFactorScore){\n\t\t\tmaxFactorScore = curFactorScore;\n\t\t}\n\t}\n\treturn maxFactorScore;\n}\n``` | 0 | 0 | ['C'] | 0 |
find-the-maximum-factor-score-of-array | scala solution | scala-solution-by-vititov-nvgn | scala []\nobject Solution {\n import scala.util.chaining._\n def maxScore(nums: Array[Int]): Long = {\n def reducer(a:(BigInt,BigInt),b:(BigInt,BigInt)) =\ | vititov | NORMAL | 2024-11-06T20:24:30.070190+00:00 | 2024-11-06T20:24:30.070221+00:00 | 1 | false | ```scala []\nobject Solution {\n import scala.util.chaining._\n def maxScore(nums: Array[Int]): Long = {\n def reducer(a:(BigInt,BigInt),b:(BigInt,BigInt)) =\n (a._1 gcd b._1, (a._2 / (a._2 gcd b._2)) * b._2)\n val pfx = nums.sorted.map(BigInt(_)).map(a => (a,a))\n .pipe{l => l.tail.scanLeft(l.head)(reducer)}\n val sfx = nums.sorted.reverse.map(BigInt(_)).map(a => (a,a))\n .pipe{l => l.tail.scanLeft(l.head)(reducer)}.reverse\n ((1 until (nums.length-1)).map(i => reducer(pfx(i-1),sfx(i+1))) ++ \n sfx.take(2) :+ pfx.last).map{case (a,b) => a*b}.max.toLong\n }\n}\n``` | 0 | 0 | ['Array', 'Prefix Sum', 'Scala'] | 0 |
find-the-maximum-factor-score-of-array | Beats 100% || Number Theory || Math|| Easy Solution. | beats-100-number-theory-math-easy-soluti-oitk | 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 | ganesh_jaggu | NORMAL | 2024-11-06T15:05:51.432458+00:00 | 2024-11-06T15:06:42.135799+00:00 | 15 | 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```cpp []\nclass Solution {\npublic:\n long long gcd(long long a,long long b){\n while(a>0 && b>0){\n if(a>b) a=a%b;\n else b=b%a;\n }\n if(a==0) return b;\n return a;\n }\n long long lcm(long long a,long long b){\n return (a/(gcd(a,b)))*b;\n }\n \n long long maxScore(vector<int>& nums) {\n long long res1 = nums[0];\n long long res2 = nums[0];\n int n = nums.size();\n if(n==0) return 1;\n if(n==1) return nums[0]*nums[0];\n vector<pair<long long,long long>> preff(n,{0,0}),suff(n,{0,0});\n preff[0] = {nums[0],nums[0]};\n suff[n - 1] = {nums[n - 1], nums[n - 1]};\n for (int i = 1; i < n; i++) {\n preff[i].second = gcd(preff[i - 1].second,nums[i]);\n preff[i].first = lcm(preff[i - 1].first, nums[i]);\n }\n for (int i = n - 2; i >= 0; i--) {\n suff[i].second = gcd(suff[i + 1].second,nums[i]);\n suff[i].first = lcm(suff[i + 1].first, nums[i]);\n }\n long long maxi = preff[n - 1].first * preff[n - 1].second;\n for(int i = 1;i< n - 1;i++){\n long long temp = gcd(preff[i - 1].second,suff[i + 1].second) * lcm(preff[i - 1].first,suff[i + 1].first);\n maxi = max(temp, maxi);\n }\n maxi = max(maxi,suff[1].first * suff[1].second);\n maxi = max(maxi,preff[n - 2].first * preff[n - 2].second); \n return maxi;\n }\n};\n``` | 0 | 0 | ['Array', 'Math', 'Suffix Array', 'Number Theory', 'Prefix Sum', 'C++'] | 0 |
find-the-maximum-factor-score-of-array | Super Simple || C++ | super-simple-c-by-lotus18-j6ci | Code\ncpp []\nclass Solution \n{\npublic:\n long long maxScore(vector<int>& nums) \n {\n int n=nums.size();\n if(n==1) return nums[0]*nums[0 | lotus18 | NORMAL | 2024-11-06T06:19:35.654048+00:00 | 2024-11-06T06:19:35.654084+00:00 | 11 | false | # Code\n```cpp []\nclass Solution \n{\npublic:\n long long maxScore(vector<int>& nums) \n {\n int n=nums.size();\n if(n==1) return nums[0]*nums[0];\n if(n==2)\n {\n long long lcm=((long long)nums[0]*nums[1])/__gcd(nums[0],nums[1]);\n int gcd=__gcd(nums[0],nums[1]);\n return max({(long long)nums[0]*nums[0],(long long)nums[1]*nums[1],lcm*gcd});\n }\n long long ans=0;\n for(int leave=-1; leave<n; leave++)\n {\n long long a=nums[0], b=nums[1], start=2;\n if(leave==0)\n {\n a=nums[1];\n b=nums[2];\n start=3;\n }\n else if(leave==1)\n {\n a=nums[0];\n b=nums[2];\n start=3;\n }\n long long gcd=__gcd(a,b);\n long long lcm=(a*b)/__gcd(a,b);\n for(int x=start; x<n; x++)\n {\n if(leave==x) continue;\n gcd=__gcd(gcd,(long long)nums[x]);\n lcm=(lcm*nums[x])/__gcd(lcm,(long long)nums[x]);\n }\n ans=max(ans,lcm*gcd);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | Best Solution || Easy to Understand | best-solution-easy-to-understand-by-nand-j6w3 | \n# Code\ncpp []\n#define ll long long\n// here we are normally calculating gcd and lcm after removing every element as the contraints are not high.\nclass Solu | NandiniJindal | NORMAL | 2024-11-06T01:36:13.926773+00:00 | 2024-11-06T01:36:13.926799+00:00 | 6 | false | \n# Code\n```cpp []\n#define ll long long\n// here we are normally calculating gcd and lcm after removing every element as the contraints are not high.\nclass Solution {\npublic:\n ll gcd(ll a,ll b){\n if(b==0) return a;\n return gcd(b,a%b);\n }\n\n ll lcm(ll a,ll b)\n {\n return a*b/gcd(a,b);\n }\n long long maxScore(vector<int>& nums) \n {\n ll n = nums.size();\n ll ans = INT_MIN;\n for(ll i=0 ; i<=n ; i++)\n {\n ll gcdd=0,lcmm=1;\n for(ll j=0 ;j <n ; j++)\n {\n if(i!=j)\n {\n gcdd = gcd(nums[j],gcdd);\n lcmm = lcm(nums[j],lcmm);\n }\n }\n ans = max(ans,gcdd*lcmm);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['Array', 'Math', 'C++'] | 0 |
find-the-maximum-factor-score-of-array | Brute Force | brute-force-by-azizkaz-plhc | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nBrute Force\n\n# Comple | azizkaz | NORMAL | 2024-11-05T06:45:57.391947+00:00 | 2024-11-05T06:45:57.391988+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nBrute Force\n\n# Complexity\n- Time complexity: $O(n^2)$\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)$$ -->\nwhere $n$ is length of the $nums$ array.\n\n# Code\n```rust []\nimpl Solution {\n pub fn max_score(nums: Vec<i32>) -> i64 {\n let n = nums.len();\n\n if n == 1 {\n return (nums[0] * nums[0]) as i64;\n }\n\n let mut r = 0;\n\n for i in 0..=n {\n r = r.max(\n Self::factor(i, &nums)\n );\n }\n\n r\n }\n\n pub fn factor(i: usize, v: &Vec<i32>) -> i64 {\n let n = v.len();\n\n let mut d = if i == 0 {v[1] as i64} else {v[0] as i64};\n let mut m = 1;\n\n for j in 0..n {\n if j != i {\n d = Self::gcd(d, v[j] as i64);\n m = Self::lcm(m, v[j] as i64);\n }\n }\n\n m*d\n }\n\n pub fn gcd(a: i64, b: i64) -> i64 {\n if a % b == 0 {\n return b;\n }\n\n Self::gcd(b, a % b)\n }\n\n pub fn lcm(a: i64, b: i64) -> i64 {\n (a * b) / Self::gcd(a, b)\n }\n}\n``` | 0 | 0 | ['Array', 'Math', 'Number Theory', 'Rust'] | 0 |
find-the-maximum-factor-score-of-array | Prefix + Suffix | prefix-suffix-by-azizkaz-3v1u | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nPrefix + Suffix\n\n# Co | azizkaz | NORMAL | 2024-11-05T06:43:32.004819+00:00 | 2024-11-05T06:49:42.333428+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nPrefix + Suffix\n\n# Complexity\n- Time complexity: $O(n)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $O(n)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nwhere $n$ is the length of the $nums$ array\n\n# Code\n```rust []\nimpl Solution {\n pub fn max_score(nums: Vec<i32>) -> i64 {\n let n = nums.len();\n\n let mut fd = vec![nums[0] as i64; n];\n let mut fm = vec![nums[0] as i64; n];\n\n let mut bd = vec![nums[n-1] as i64; n];\n let mut bm = vec![nums[n-1] as i64; n];\n\n for i in 1..n {\n fd[i] = Self::gcd(fd[i-1], nums[i] as i64);\n fm[i] = Self::lcm(fm[i-1], nums[i] as i64);\n\n bd[n-i-1] = Self::gcd(bd[n-i], nums[n-i-1] as i64);\n bm[n-i-1] = Self::lcm(bm[n-i], nums[n-i-1] as i64);\n }\n\n let mut r = (fd[n-1] * fm[n-1]);\n\n if n >= 2 {\n r = r.max(fd[n-2] * fm[n-2]);\n r = r.max(bd[1] * bm[1])\n } \n\n for i in (2..n).rev() {\n let mut d = Self::gcd(bd[i], fd[i-2]);\n let mut m = Self::lcm(bm[i], fm[i-2]); \n\n r = r.max(d * m); \n }\n\n r\n }\n\n pub fn gcd(a: i64, b: i64) -> i64 {\n if a % b == 0 {\n return b;\n }\n\n Self::gcd(b, a % b)\n }\n\n pub fn lcm(a: i64, b: i64) -> i64 {\n (a * b) / Self::gcd(a, b)\n }\n}\n``` | 0 | 0 | ['Array', 'Math', 'Number Theory', 'Rust'] | 0 |
find-the-maximum-factor-score-of-array | Short Ruby solution. No libraries. | short-ruby-solution-no-libraries-by-oneu-0544 | Intuition\nStraight forward\n\n# Approach\nBrute-force\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(1)\n\n# Code\nruby []\n# @param {In | oneunknownuser | NORMAL | 2024-11-03T18:41:18.296273+00:00 | 2024-11-04T23:40:34.044375+00:00 | 3 | false | # Intuition\nStraight forward\n\n# Approach\nBrute-force\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$\n\n- Space complexity:\n$$O(1)$$\n\n# Code\n```ruby []\n# @param {Integer[]} nums\n# @return {Integer}\ndef max_score(nums)\n n = nums.size \n return 0 if n == 0\n return nums[0] * nums[0] if n == 1\n \n max = reducer(:lcm, nums, 1) * reducer(:gcd, nums, 1)\n\n nums.each_with_index do |v, idx|\n (nums[0], nums[idx]) = [nums[idx], nums[0]] # swap a head\n max = [reducer(:lcm, nums) * reducer(:gcd, nums), max].max\n end\n\n max\nend\n\ndef gcd(a, b)\n b == 0 ? a : gcd(b, a % b)\nend\n\ndef lcm(a, b)\n a == 0 || b == 0 ? a : a * b / gcd(a, b)\nend\n\ndef reducer(mtd, arr, shift = 0)\n arr[(2 - shift)..].reduce(arr[1 - shift]) { |el, res| res = method(mtd).call(res, el) }\nend\n``` | 0 | 0 | ['Ruby'] | 0 |
find-the-maximum-factor-score-of-array | Prime Factorisation | O(𝑛²), O(𝑛) | 5.83%, 59.60% | prime-factorisation-on2-on-583-5960-by-w-1qh5 | Intuition\n Describe your first thoughts on how to solve this problem. \nThis problem involves finding the lowest common multiple (LCM) and the greatest common | Winoal875 | NORMAL | 2024-11-03T15:02:02.739310+00:00 | 2024-11-17T19:24:57.805252+00:00 | 5 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis problem involves finding the lowest common multiple (LCM) and the greatest common divider (GCD) [or highest common factor (HCF)] of the entire array minus one or no elements. Our approach uses <ins>number theory</ins> by first doing **prime factorisation** on all numbers, then comparing using factors to find the LCM and GCD/HCF of the array, for each scenario when one element is removed, and when none is removed. We can then multiply the LCM and GCD/HCF to get the factor score of each scenario, which we take the max factor score as the final answer.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Prime Factorization: For each number in `nums`, store its prime factors and their counts.\n- LCM Calculation: The LCM will be the product of all the factors.\n- GCD Calculation: The GCD will be the product of all the common factors.\n- Compute LCM and GCD for the entire array without exclusions, and for subsets where each element is excluded one at a time.\n- Calculate Factor Score: Multiply LCM and GCD for each subset, keeping the maximum result.\n# Complexity\n*where $n$ is length of the list `nums`*.\n- **Time complexity: O(\uD835\uDC5B\xB2)**\nDue to passing through all $$n$$ elements to calculate LCM and GCD for each subset, and calculating $$n$$ different subsets where a different element is excluded each time.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- **Space complexity: O(\uD835\uDC5B)**\nFor storing frequency dictionaries of each element\u2019s prime factors.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n| Runtime | Memory |\n| -------- | ------- |\n| **143** ms | beats **5.83%** | **16.75** MB | beats **59.60%**|\n```python3 []\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n import math\n from collections import Counter\n\n n = len(nums)\n if n == 0:\n return 0\n if n == 1:\n return nums[0] ** 2\n\n def get_factors(num):\n freq_dict = Counter()\n while num > 1:\n if num < 4:\n freq_dict[num] += 1\n break\n prime = True\n for i in range(2, (num // 2) + 1):\n if num % i == 0:\n freq_dict[i] += 1\n num = num // i\n prime = False\n break\n if prime == True:\n freq_dict[num] += 1\n break\n return dict(freq_dict)\n\n arr_of_freq_dict = []\n\n for num in nums:\n arr_of_freq_dict.append(get_factors(num))\n # print(arr_of_freq_dict)\n\n def LCM(arr_of_freq_dict, n, excluded_idx):\n output = 1\n mydict = {}\n # print("arr",arr_of_freq_dict)\n for i in range(n):\n if i == excluded_idx:\n continue\n for key in arr_of_freq_dict[i]:\n # print(i,": key",key)\n if key not in mydict or arr_of_freq_dict[i][key] > mydict[key]:\n mydict[key] = arr_of_freq_dict[i][key]\n # print(key, mydict[key])\n # print(mydict, excluded_idx)\n for key in mydict:\n output *= key ** mydict[key]\n return output\n\n def GCD(arr_of_freq_dict, n, excluded_idx):\n output = 1\n start = True\n for i in range(n):\n if i == excluded_idx:\n continue\n if start == True:\n mydict = arr_of_freq_dict[i].copy()\n start = False\n continue\n tempdict = mydict.copy()\n for key in tempdict:\n if key not in arr_of_freq_dict[i]:\n del mydict[key]\n else:\n if arr_of_freq_dict[i][key] < mydict[key]:\n mydict[key] = arr_of_freq_dict[i][key]\n for key in mydict:\n output *= key ** mydict[key]\n return output\n\n lcm, gcd = LCM(arr_of_freq_dict, n, n + 1), GCD(arr_of_freq_dict, n, n + 1)\n score = lcm * gcd\n # print(lcm,gcd)\n for i in range(n):\n this_lcm, this_gcd = LCM(arr_of_freq_dict, n, i), GCD(\n arr_of_freq_dict, n, i\n )\n # print(this_lcm, this_gcd)\n this_score = this_lcm * this_gcd\n if this_score > score:\n score = this_score\n\n if n == 2:\n return max(nums[0] ** 2, nums[1] ** 2, score)\n return score\n```\n# Detailed Approach\n1. Prime Factorization Function (`get_factors()`):\n - Calculates prime factors of each number `num` using trial division up to $\\sqrt{num}$.\n - Stores results in a frequency dictionary for each number, storing all the frequency dictionaries (prime factors) in a list of frequency dictionaries `arr_of_freq_dict`.\n2. LCM Calculation (`LCM()`):\n - Initializes an empty dictionary `mydict` to track the highest power of each prime factor across included elements.\n - Skips the excluded index.\n - For each factor in each number, updates `mydict` with the highest exponent of each prime.\n - Multiplies all factors in `mydict` to get the LCM.\n3. GCD Calculation (`GCD()`):\n - Initializes `mydict` with factors of the first non-excluded element.\n - For each included element, finds the minimum exponent for overlapping prime factors between `mydict` and the element.\n - Multiplies factors in `mydict` to get the GCD.\n4. Score Calculation:\n - Computes the factor score (LCM $\\times$ GCD) for the full array.\n - Iteratively excludes each element, calculates LCM and GCD to get its factor score, and tracks the maximum score.\n\n# Detailed Complexity Breakdown\n### Time Complexity: $O(\uD835\uDC5B^2)$\n1. Prime Factorization: \n - Each number `num` in nums is factorized up to its square root, thus taking $O(\\sqrt{\\text{num}})$ time.\n2. LCM Function: \n - Each LCM call, compares all $$n$$ elements\' prime factors, taking $O(n\u0393^{\u22121}(\\text{max(num})))$ = $O(n)$ time.\n - *[see next section on detailed Space Complexity for more details on why number of prime factors $\u0393^{\u22121}(\\text{num})$ is constant.]*\n3. GCD Function: \n - Similarly, each GCD call compares all $$n$$ elements\' prime factors, taking $O(n\u0393^{\u22121}(\\text{max(num})))$ = $O(n)$ time.\n - *[see next section on detailed Space Complexity for more details on why number of prime factors $\u0393^{\u22121}(\\text{num})$ is constant.]*\n4. Score Calculation (Outer Loop):\n - LCD and GCD and subsequently the factor score (product of LCM and GCD) is calculated for $n$ scenarios where each element is removed, taking $O(n)$ in the outer loop.\n\n### Space Complexity: $O(\uD835\uDC5B)$\n1. Prime Factor Dictionaries `arr_of_freq_dict`: \n - We store prime factors for $n$ elements, thus taking $O(n\u0393^{\u22121}(\\text{max(num})))$ = $O(n)$ space.\n - Note that each element `num` will have up to $\u0393^{\u22121}(\\text{num})$ factors which is the inverse factorial, which can be estimated to a constant.\n - Eg. If $\\text{num} = 20!$, then number of factors = 20 ($20!=1\\times 2\\times ... \\times 20$). Note that its number of prime factors will be even less at 8 ($20!=2^{18}\\times3^8\\times5^4\\times7^2\\times11^1\\times13^1\\times17^1\\times19^1$). Hence, the number of prime factors per element can be treated as constant.\n2. LCM/GCD Temporary Dictionaries `mydict` :\n - `mydict` is constant sized, as it takes up to $O(\u0393^{\u22121}(\\text{max(num})))$ = $O(1)$ space to store prime factors.\n\n# Best, Worst, and Average Case Analysis\n### Time Complexity\nFor all cases, $n$ elements will be looped through to consider the exclusion of that element, and for each excluded element, $n$ other elements\' frequency dictionaries of prime factors will be used to compute the LCM and GCD. As we have established in the detailed space complexity section that the number of prime factors in a number can be estimated to be constant, all cases will be $O(n^2)$ time for the overall computing of LCM and GCDs. What may vary is the time complexity for the initial prime factorisation step.\n1. Best-case: $O(n\\text{log}(\\text{num}) + n^2)$ = $O(n^2)$\n - Each number is an exponent of 2, taking $\\log(num)$ time to break down to its prime factor.\n2. Worst-case: $O(n\\sqrt{\\text{num}} + n^2)$ = $O(n^2)$\n - Each number is prime, and requires $\\sqrt{\\text{num}}$ time to determine it has no prime factor other than itself..\n3. Average-case: $O(n\\sqrt{\\text{num}} + n^2)$ = $O(n^2)$\n - On average, each number has to go through a number of passes and divisions before it is broken down into its prime factor(s).\n### Space Complexity\n1. All cases: $O(n)$\n - For all cases, all $n$ elements\' frequency dictionaries of prime factors are stored. In the best case, each number has minimal prime factors (eg. the number is a prime). In the worst case, each number has multiple prime factors. However, as we have established in the detailed space complexity section that the number of prime factors in a number can be estimated to be constant, all cases will be $O(n)$ space complexity for $n$ frequency dictionaries.\n### Summary\n| Scenario | Time Complexity | Space Complexity |\n| - | - | - |\n| Best Case | $O(n^2)$ | $O(n)$ |\t\n| Worst Case | $O(n^2)$ | $O(n)$ |\n| Average Case | $O(n^2)$ | $O(n)$ |\n***\nCheck out my solutions to other problems here! \uD83D\uDE03\n*https://leetcode.com/discuss/general-discussion/5942132/my-collection-of-solutions*\n*** | 0 | 0 | ['Math', 'Number Theory', 'Python3'] | 0 |
find-the-maximum-factor-score-of-array | Find the Maximum Factor Score of Array | find-the-maximum-factor-score-of-array-b-kgo3 | 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 | zH6HvQOmcZ | NORMAL | 2024-11-03T04:14:52.168012+00:00 | 2024-11-03T04:14:52.168041+00:00 | 4 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\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 maxScore(self, nums: List[int]) -> int:\n\n n, ctr = len(nums), Counter(nums)\n\n mx = gcd(*nums) * lcm(*nums)\n \n if n > 1:\n\n for i in range(n):\n if ctr[nums[i]] > 1: continue\n\n arr = nums[:i] + nums[i+1:]\n mx = max(mx, gcd(*arr) * lcm(*arr))\n \n return mx\n``` | 0 | 0 | ['Python3'] | 0 |
find-the-maximum-factor-score-of-array | Find the Maximum Factor Score of Array | find-the-maximum-factor-score-of-array-b-p6cf | 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 | zH6HvQOmcZ | NORMAL | 2024-11-03T04:14:48.940976+00:00 | 2024-11-03T04:14:48.941002+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\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 maxScore(self, nums: List[int]) -> int:\n\n n, ctr = len(nums), Counter(nums)\n\n mx = gcd(*nums) * lcm(*nums)\n \n if n > 1:\n\n for i in range(n):\n if ctr[nums[i]] > 1: continue\n\n arr = nums[:i] + nums[i+1:]\n mx = max(mx, gcd(*arr) * lcm(*arr))\n \n return mx\n``` | 0 | 0 | ['Python3'] | 0 |
find-the-maximum-factor-score-of-array | Simple Python | simple-python-by-amruthamuralidhar-lo38 | Intuition\ncalculate gcd and lcm each time by removing one element\n\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(n)\n\n# Code\npython3 []\nc | AmruthaMuralidhar | NORMAL | 2024-11-02T14:17:46.450864+00:00 | 2024-11-02T14:17:46.450891+00:00 | 8 | false | # Intuition\ncalculate gcd and lcm each time by removing one element\n\n# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(n)\n\n# Code\n```python3 []\nclass Solution:\n import math\n def maxScore(self, nums: List[int]) -> int:\n mx = gcd(*nums) * lcm(*nums)\n for i in nums:\n tc = nums.copy()\n tc.remove(i)\n temp = gcd(*tc)*lcm(*tc)\n if mx<temp:\n mx = temp\n return mx\n \n``` | 0 | 0 | ['Python3'] | 0 |
find-the-maximum-factor-score-of-array | Fast solurtion C# | fast-solurtion-c-by-bogdanonline444-06x6 | \n# Complexity\n- Time complexity: O(n ^ 2)\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) | bogdanonline444 | NORMAL | 2024-11-02T10:59:21.911109+00:00 | 2024-11-02T10:59:21.911130+00:00 | 0 | false | \n# Complexity\n- Time complexity: O(n ^ 2)\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```csharp []\npublic class Solution {\n public long MaxScore(int[] nums) {\n if(nums.Length == 1)\n {\n return (long)nums[0] * nums[0];\n }\n long max = 0;\n long gcd = nums[0];\n long lcm = nums[0];\n for(int i = 1; i < nums.Length; i++)\n {\n gcd = GCD(gcd, nums[i]);\n lcm = LCM(lcm, nums[i]);\n }\n max = lcm * gcd;\n for(int i = 0; i < nums.Length; i++)\n {\n long currGCD = 0;\n long currLCM = 1;\n for(int j = 0; j < nums.Length; j++)\n {\n if(j == i)\n {\n continue;\n }\n currGCD = currGCD == 0 ? nums[j] : GCD(currGCD, nums[j]);\n currLCM = LCM(currLCM, nums[j]);\n }\n max = Math.Max(max, currLCM * currGCD);\n }\n return max;\n }\n\n public long GCD (long first, long second)\n {\n while(second != 0)\n {\n long temp = second;\n second = first % second;\n first = temp;\n }\n return first;\n }\n\n public long LCM (long first, long second)\n {\n return first * second / (GCD(first, second));\n }\n}\n```\n\n | 0 | 0 | ['Array', 'Math', 'C#'] | 0 |
find-the-maximum-factor-score-of-array | Simple Java Solution | simple-java-solution-by-sakshikishore-7zwi | Code\njava []\nclass Solution {\n public long maxScore(int[] nums) {\n long max=0;\n for(int i=0;i<nums.length;i++)\n {\n int flag= | sakshikishore | NORMAL | 2024-11-02T09:23:58.417011+00:00 | 2024-11-02T09:23:58.417040+00:00 | 4 | false | # Code\n```java []\nclass Solution {\n public long maxScore(int[] nums) {\n long max=0;\n for(int i=0;i<nums.length;i++)\n {\n int flag=0;\n long gcd=0,lcm=0;\n for(int j=0;j<nums.length;j++)\n {\n if(i==j)\n {\n continue;\n }\n else\n {\n if(flag==0)\n {\n gcd=nums[j];\n lcm=nums[j];\n flag=1;\n }\n else\n {\n long a=gcd,b=nums[j];\n while(b>0)\n {\n long r=a%b;\n a=b;\n b=r;\n }\n gcd=a;\n a=lcm;\n b=nums[j];\n while(b>0)\n {\n long r=a%b;\n a=b;\n b=r;\n }\n\n lcm=(lcm*nums[j])/a;\n \n }\n }\n }\n if(lcm*gcd>max)\n {\n System.out.println(lcm+" || "+gcd);\n max=lcm*gcd;\n }\n }\n long gcd=nums[0],lcm=nums[0];\n for(int j=1;j<nums.length;j++)\n {\n long a=lcm,b=nums[j];\n while(b>0)\n {\n long r=a%b;\n a=b;\n b=r;\n }\n lcm=(lcm*nums[j])/a;\n\n a=gcd;\n b=nums[j];\n while(b>0)\n {\n long r=a%b;\n a=b;\n b=r;\n }\n gcd=a;\n\n\n \n }\n if(lcm*gcd>max)\n {\n max=lcm*gcd;\n }\n \n return max;\n \n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-the-maximum-factor-score-of-array | Simple Java Solution | simple-java-solution-by-rajatgandhi333-p591 | Intuition\n Describe your first thoughts on how to solve this problem. \nBrute force, find the gcd and lcm of the array\nand compare when one element is removed | rajatgandhi333 | NORMAL | 2024-11-02T08:49:18.924477+00:00 | 2024-11-02T08:49:18.924504+00:00 | 6 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nBrute force, find the gcd and lcm of the array\nand compare when one element is removed\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public long maxScore(int[] nums) {\n //edge case\n if (nums.length == 1) {\n return(long) nums[0] * nums[0];\n }\n long initialGCD = gcdOfArray(nums, -1);\n long initialLCM = lcmOfArray(nums, -1);\n long maxScore = initialGCD * initialLCM;\n\n for (int i = 0; i < nums.length; i++) {\n long gcd = gcdOfArray(nums, i);\n long lcm = lcmOfArray(nums, i);\n long currentScore = gcd * lcm;\n maxScore = Math.max(currentScore, maxScore);\n }\n\n return maxScore;\n }\n\n private long gcd(long a, long b) {\n //base case\n if (b == 0) return a;\n return gcd(b, a % b);\n }\n\n private long lcm(long a, long b) {\n //formula based\n return (a * b) / gcd(a, b);\n }\n\n private long gcdOfArray(int[] arr, int exclude) {\n long result = -1;\n\n for (int i = 0; i < arr.length; i++) {\n if (i == exclude) continue;//skip\n\n if (result == -1) {\n result = arr[i];\n } else {\n result = gcd(result, arr[i]);\n }\n }\n\n return result;\n }\n\n private long lcmOfArray(int[] arr, int exclude) {\n long result = -1;\n for (int i = 0; i < arr.length; i++) {\n if (i == exclude) continue;\n if (result == -1) {\n result = arr[i];\n } else {\n result = lcm(result, arr[i]);\n }\n }\n return result;\n }\n\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-the-maximum-factor-score-of-array | Easiest and Self Explanatory Solution || Brute Force | easiest-and-self-explanatory-solution-br-586p | \n\n# Code\ncpp []\nclass Solution {\npublic:\n long long computelcm(long long a, long long b) {\n return (a * b) / __gcd(a,b);\n }\n\n\n long l | karan_maheshwari16 | NORMAL | 2024-11-02T07:04:36.964275+00:00 | 2024-11-02T07:05:03.527166+00:00 | 8 | false | \n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long computelcm(long long a, long long b) {\n return (a * b) / __gcd(a,b);\n }\n\n\n long long maxScore(vector<int>& nums) {\n long long ans = 0;\n long long gcd = 0, lcm = 0;\n int n = nums.size();\n\n for(int i=0 ; i<n ; i++) {\n long long overall_gcd = 0;\n long long overall_lcm = 1;\n\n for(int j=0 ; j<n ; j++) {\n overall_gcd = __gcd(overall_gcd, (long long)nums[j]);\n overall_lcm = computelcm(overall_lcm, (long long)nums[j]);\n }\n ans = max(ans, overall_gcd * overall_lcm);\n }\n\n\n for(int i=0 ; i<n ; i++) {\n long long g = 0, l =1;\n for(int j=0 ; j<n ; j++) {\n if(i == j) continue;\n else {\n g = __gcd(g, (long long)nums[j]);\n l = computelcm(l, (long long)nums[j]); \n }\n }\n ans = max(ans, g * l);\n\n }\n\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | C++ Easy Solution. | c-easy-solution-by-sujay_awale-sv7z | \n# Code\ncpp []\nclass Solution {\npublic:\n long long maxScore(vector<int>& nums) {\n long long ans=0, gcd1=0, lcm1=0;\n // Removing no eleme | sujay_awale | NORMAL | 2024-11-01T16:18:03.964161+00:00 | 2024-11-01T16:18:03.964191+00:00 | 24 | false | \n# Code\n```cpp []\nclass Solution {\npublic:\n long long maxScore(vector<int>& nums) {\n long long ans=0, gcd1=0, lcm1=0;\n // Removing no element\n for(int i=0; i<nums.size(); i++){\n if(gcd1==0){gcd1=1LL*nums[i];}\n else{gcd1=__gcd(gcd1, 1LL*nums[i]);}\n if(lcm1==0){lcm1=nums[i];}\n else{lcm1=(lcm1*nums[i])/__gcd(lcm1,1LL*nums[i]);}\n }\n ans=lcm1*gcd1;\n // Removing atmost one element\n for(int i=0; i<nums.size(); i++){\n long long gcd=0, lcm=0;\n for(int j=0; j<nums.size(); j++){\n if(i!=j){\n if(gcd==0){gcd=1LL*nums[j];}\n else{gcd=__gcd(gcd, 1LL*nums[j]);}\n if(lcm==0){lcm=nums[j];}\n else{lcm=(lcm*nums[j])/__gcd(lcm,1LL*nums[j]);}\n }\n }\n ans=max(ans, (lcm*gcd));\n }\n return ans;\n }\n};\n\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | 100% beat | 100-beat-by-maancodes-76kd | 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 | Maancodes | NORMAL | 2024-11-01T08:47:29.156644+00:00 | 2024-11-01T08:47:29.156690+00:00 | 15 | 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```cpp []\nclass Solution {\npublic:\n long long gcd(long long a,long long b){\n while(a>0 && b>0){\n if(a>b) a=a%b;\n else b=b%a;\n }\n if(a==0) return b;\n return a;\n }\n long long lcm(long long a,long long b){\n return (a/(gcd(a,b)))*b;\n }\n long long maxScore(vector<int>& nums) {\n int n = nums.size();\n if(n==0) return 1;\n if(n==1) return nums[0]*nums[0];\n \n vector<long long> g1(n);\n vector<long long> g2(n);\n vector<long long> l1(n);\n vector<long long> l2(n);\n\n g1[0] = nums[0];\n l1[0] = nums[0];\n for(int i=1;i<n;i++){\n g1[i] = gcd(g1[i-1],nums[i]);\n l1[i] = lcm(l1[i-1],nums[i]);\n }\n\n g2[n-1] = nums[n-1];\n l2[n-1] = nums[n-1];\n for(int i=n-2;i>=0;i--){\n g2[i] = gcd(g2[i+1],nums[i]);\n l2[i] = lcm(l2[i+1],nums[i]);\n }\n \n long long maxi = g1[n-1]*l1[n-1];\n\n for(int i=1;i<n-1;i++){\n long long temp = gcd(g1[i-1],g2[i+1]) * lcm(l1[i-1],l2[i+1]);\n maxi = max(maxi,temp);\n }\n\n maxi = max(maxi,g1[n-2]*l1[n-2]);\n maxi = max(maxi,g2[1]*l2[1]);\n return maxi;\n \n }\n};\n``` | 0 | 0 | ['Math', 'Prefix Sum', 'C++'] | 0 |
find-the-maximum-factor-score-of-array | Python3 Brute Force | python3-brute-force-by-tkr_6-m9ni | \n\n# Code\npython3 []\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n\n ans=lcm(*nums)*gcd(*nums)\n n=len(nums)\n\n fo | TKR_6 | NORMAL | 2024-11-01T07:12:20.231983+00:00 | 2024-11-01T07:12:20.232007+00:00 | 14 | false | \n\n# Code\n```python3 []\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n\n ans=lcm(*nums)*gcd(*nums)\n n=len(nums)\n\n for i in range(n):\n sub=nums[:i]+nums[i+1:]\n l=lcm(*sub)\n g=gcd(*sub)\n ans=max(ans,l*g)\n \n return ans\n \n``` | 0 | 0 | ['Math', 'Python', 'Python3'] | 0 |
find-the-maximum-factor-score-of-array | Easy to understand C++ code | easy-to-understand-c-code-by-rk_25-vnmx | 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 | RK_25 | NORMAL | 2024-11-01T06:55:31.794034+00:00 | 2024-11-01T06:55:31.794068+00:00 | 9 | 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```cpp []\nclass Solution {\npublic:\n long long HCF(vector<int>& nums)\n {\n int l = nums.size();\n long long num2 = nums[l-1];\n for(int i = l-2; i>=0; i--)\n {\n long long num1 = nums[i];\n \n long long hcf;\n long long temp = num1;\n if(num1>num2)\n {\n num1 = num2;\n num2 = temp;\n }\n // long long newnum1 = num1, newnum2 = num2;\n // while(newnum1!=0 && newnum2%newnum1!=0)\n // {\n // newnum1 = newnum2%newnum1;\n // newnum2 = num1;\n // num1 = newnum1;\n // }\n num2 = gcd(num1, num2);\n // hcf = newnum1;\n }\n return num2;\n }\n\n long long LCM(vector<int>& nums)\n {\n int l = nums.size();\n long long num2 = nums[l-1];\n for(int i = l-2; i>=0; i--)\n {\n long long num1 = nums[i];\n \n long long lcm = (num1*num2)/(gcd(num1, num2));\n // for(lcm = max(num1, num2); lcm<=num1*num2; lcm++)\n // {\n // if(lcm%num1==0 && lcm%num2==0)\n // {\n // num2 = lcm;\n // break;\n // }\n // }\n num2 = lcm;\n }\n return num2;\n }\n long long maxScore(vector<int>& nums) {\n int l = nums.size();\n long long lcm, hcf;\n long long ans = 0;\n if(nums.size()==1)\n return nums[0]*nums[0];\n for(int i = -1; i<l; i++)\n {\n int notaken = 0;\n if(i>=0){ \n notaken = nums[i];\n nums.erase(nums.begin()+i);\n }\n long long prod = LCM(nums)*HCF(nums);\n ans = max(ans, prod);\n if(i>=0)\n nums.insert(nums.begin()+i, notaken);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | Maximize Factor Score of an Array After Removing One Element | maximize-factor-score-of-an-array-after-t3fp9 | Intuition\n Describe your first thoughts on how to solve this problem. \nThe factor score is defined as the product of the LCM and GCD of the array. Removing on | i-sayankh | NORMAL | 2024-10-31T03:51:40.508176+00:00 | 2024-10-31T03:51:40.508212+00:00 | 17 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe factor score is defined as the product of the LCM and GCD of the array. Removing one element from the array may increase the factor score by changing the GCD and LCM in ways that maximize their product. We aim to explore all possible configurations by either keeping the entire array or removing one element at a time.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initial Calculations:\n- Calculate the GCD and LCM for the entire array.\n- Store their product as the initial factor score.\n\n2. Removing Elements:\n- For each element, create a new array excluding that element.\n- Compute the GCD and LCM of the new array.\n- Calculate the factor score (GCD * LCM) for the new array and update the maximum score if it is higher than the previous maximum.\n\n3. Return the Maximum Score:\nAfter iterating through all configurations (including no removal), return the highest factor score obtained.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity is $$O(n^2)$$, where n is the length of the array. This is because we calculate the GCD and LCM of a new array of length $$n \u2212 1$$ for each element removed. The `reduce` calls for each of these configurations make this approach quadratic.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nThe space complexity is $$O(n)$$, primarily due to the storage of intermediate arrays and calculations for GCD and LCM.\n# Code\n```javascript []\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar maxScore = function(nums) {\n if (nums.length === 1) {\n return nums[0] * nums[0];\n }\n\n const totalGCD = calculateGCDOfArray(nums);\n const totalLCM = calculateLCMOfArray(nums);\n let maxScore = totalGCD * totalLCM;\n\n for (let i = 0; i < nums.length; i++) {\n const newNums = nums.slice(0, i).concat(nums.slice(i + 1));\n const currentGCD = calculateGCDOfArray(newNums);\n const currentLCM = calculateLCMOfArray(newNums);\n const currentScore = currentGCD * currentLCM;\n \n maxScore = Math.max(maxScore, currentScore);\n }\n\n return maxScore;\n};\n\nfunction gcd(a, b) {\n while (b !== 0) {\n [a, b] = [b, a % b];\n }\n return a;\n}\n\nfunction lcm(a, b) {\n return (a * b) / gcd(a, b);\n}\n\nfunction calculateGCDOfArray(arr) {\n return arr.reduce((acc, num) => gcd(acc, num));\n}\n\nfunction calculateLCMOfArray(arr) {\n return arr.reduce((acc, num) => lcm(acc, num));\n}\n``` | 0 | 0 | ['JavaScript'] | 0 |
find-the-maximum-factor-score-of-array | C++ | Brute Force Solution | Clean Code ✅ | Beginner Friendly | c-brute-force-solution-clean-code-beginn-rwdv | Time complexity is\n - due to outer loop = N\n - due to inner loop = N\n - for gcd function = log(min(a, b)) , since a and b can be at max 30, the comp | Felix-Felicis | NORMAL | 2024-10-30T20:25:04.608962+00:00 | 2024-10-30T20:25:04.608997+00:00 | 15 | false | Time complexity is\n - due to outer loop = N\n - due to inner loop = N\n - for gcd function = log(min(a, b)) , since a and b can be at max 30, the complexity becomes =~ log 30 =~ constant\n \n TC - O(N^2)\n SC - O(1)\n\n# Code\n```cpp []\nclass Solution {\npublic:\n\n // optimized Euclidean algorithm for GCD \n long long getGCD(long long a, long long b){\n\n if(a==0) return b;\n if(b==0) return a;\n\n if(a>b) return getGCD(a%b, b);\n\n return getGCD(a, b%a);\n }\n\n long long getLCM(long long a, long long b){\n if(a==b) return a;\n return (a*b)/getGCD(a, b);\n }\n\n long long maxScore(vector<int>& nums) {\n\n if(nums.size() == 1) return nums[0]*nums[0];\n\n long long maxFactor = 0;\n\n // i is for tracking the element to be removed. In other words, we\'ll remove the (i-1)th number from array\n // j is to loop over the array\n for(int i=0; i<=nums.size(); i++){\n \n // initialize lcm and gcd\n long long lcm, gcd;\n if(i==1) {lcm = nums[1]; gcd = nums[1];}\n else {lcm = nums[0]; gcd = nums[0];}\n\n for(int j=0; j<nums.size(); j++){\n \n if(i-1==j) continue; // don\'t consider i-1th element\n\n lcm = getLCM(lcm, nums[j]);\n gcd = getGCD(gcd, nums[j]);\n \n }\n\n maxFactor = max(maxFactor, lcm*gcd);\n }\n\n return maxFactor;\n }\n\n};\n``` | 0 | 0 | ['Math', 'Number Theory', 'C++'] | 0 |
find-the-maximum-factor-score-of-array | JAVA 1ms with GCD | java-1ms-with-gcd-by-meringueee-k7zr | 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 | meringueee | NORMAL | 2024-10-30T10:19:43.532625+00:00 | 2024-10-30T10:19:43.532664+00:00 | 16 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public long maxScore(int[] n) {\n if(n.length==1)return n[0]*n[0];\n long[] rg = new long[n.length];\n long[] rl = new long[n.length];\n\n rg[n.length-1]=rl[n.length-1]=n[n.length-1];\n\n for(int i=n.length-2; i>=0; i--){\n rg[i]=gcd(rg[i+1],n[i]);\n rl[i]=rl[i+1]*n[i]/gcd(rl[i+1],n[i]);\n }\n long a = Math.max(rg[0]*rl[0], rg[1]*rl[1]);\n\n long lg=n[0], ll=n[0], t;\n for(int i=1; i<n.length-1; i++){\n t = gcd(lg,rg[i+1]) * (ll*rl[i+1])/gcd(ll,rl[i+1]);\n if(a<t)a=t;\n lg=gcd(lg, n[i]);\n ll=ll*n[i]/gcd(ll,n[i]);\n }\n return Math.max(a, lg*ll);\n }\n private long gcd(long a, long b){\n if(b%a==0)return a;\n return gcd(b%a, a);\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-the-maximum-factor-score-of-array | Time: O(n) , Space : O(n) , 2 pass , C++ | time-on-space-on-2-pass-c-by-gearman0712-1moq | Intuition\nIterate through the array , leave current element and calculate gcd and lcm for all the remaining elements.\nBut it would take O(n^2).\nIf you look | gearman0712 | NORMAL | 2024-10-30T10:11:40.910145+00:00 | 2024-10-30T10:11:40.910176+00:00 | 9 | false | # Intuition\nIterate through the array , leave current element and calculate gcd and lcm for all the remaining elements.\nBut it would take O(n^2).\nIf you look closely you will find redundent work , why can\'t we calculate in the starting and save these answers in suffix arrays.\n\nNo need to create prefix array we can use variables to store lcm and gcd from start.\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\no(n)\n\n# Code\n```cpp []\n# define ll long long\nclass Solution {\npublic:\n long long maxScore(vector<int>& nums) {\n\n int n = nums.size();\n\n if(n==1)\n return nums[0]*nums[0];\n\n\n vector<ll> gcdFromBack(n);\n vector<ll> lcmFromBack(n);\n ll g =0, l=1;\n\n for(int i=n-1 ;i>=0 ;--i)\n { \n g= __gcd(g, (ll)nums[i]);\n l = (l/__gcd(l,(ll)nums[i])*nums[i]);\n gcdFromBack[i] =g ;\n lcmFromBack[i] = l;\n \n }\n\n ll gmax = g*l;\n g=0 , l=1;\n \n\n for(int i=0 ;i<n ;i++)\n { \n ll gmerge = i== n-1?g: __gcd(g, gcdFromBack[i+1] );\n ll lmerge = i== n-1?l: (l /__gcd(l ,lcmFromBack[i+1]) * lcmFromBack[i+1]); // to avoid overflow , l is a bigger so divide it alone by gcd\n gcdFromBack[i] =g ;\n gmax = max (gmax , gmerge*lmerge );\n \n g= __gcd(g, (ll)nums[i]);\n l = (l*nums[i])/__gcd(l,(ll)nums[i]);\n \n }\n \n return gmax ;\n \n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | Max Score with Brute Force lcm*gcd | max-score-with-brute-force-lcmgcd-by-roh-zv4h | Intuition\n Describe your first thoughts on how to solve this problem. \nAs the Questions says that we find the maximum score that is equal to product of lcm of | rohitsinghmaurya20 | NORMAL | 2024-10-30T08:14:38.266549+00:00 | 2024-10-30T08:14:38.266572+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs the Questions says that we find the maximum score that is equal to product of lcm of array elements and gcd of the array elements and we can remove at most one element.\nThen first thing which come in my mind that according to constraint solution will be accepeted in 0(n^2) so I create all possible array with excluding the one element and first array with non exclude any element and then calculate, gcd and lcm of array and find product of lcm and gcd and store the maximum value of product in ans.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nfirt run a loop i = -1 to i < n and in loop create a vector res\nand run another loop inside the first loop and if i != j then store that element in the res. Thus we find all possible vector of elements\n\nmake a function max_fector(res) and store the value of the function in p and find the ans = max(ans , p).\n\nIn max_factor function calculate the gcd of the array element using Euclidian Algorithm of gcd and calculate lcm of the array elements in another function lcm_arr with parameters res vector and starting index 0. Since lcm of two numbers a , b is equal to the (a*b)/gcd(a,b), Thus I find lcm of all array elements which is store in lcm variable and ans = lcm*gcd of array and return ans in max_factor.\nFinally in maxScore function maximize the score and return as the final answer in maxScore function.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n I run two loop of n*n = o(n^2)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n I use a vector which store n - 1 elements minimum and n elements maximum so space complexity is o(n).\n\n# Code\n```cpp\n\nclass Solution {\n\nprivate:\n\nlong long gcd(long long a , long long b){\n if(b == 0)return a;\n return gcd(b , a%b);\n}\n\nlong long lcm_arr(vector<long long>&res , int ind){\n if(ind == res.size()-1)return res[ind];\n long long a = res[ind];\n long long b = lcm_arr(res , ind+1);\n return (a*b/gcd(a,b));\n\n}\n\nlong long max_factor(vector<long long>&res){\n \n long long gcd1 = res[0];\n for(int i = 1 ; i < res.size() ; i++){\n gcd1 = gcd(gcd1 , res[i]);\n }\n long long lcm = lcm_arr(res , 0);\n\n long long ans = lcm*gcd1;\n return ans;\n}\n\npublic:\n long long maxScore(vector<int>& nums) {\n\n if(nums.size()==1)return nums[0]*nums[0];\n \n long long n = nums.size();\n long long ans = 0;\n\n for(int i = -1 ; i < n ; i++){\n vector<long long>res;\n\n for(int j = 0 ; j < n ; j++){\n if(i != j)res.push_back(nums[j]);\n }\n\n long long p = max_factor(res);\n ans = max(ans , p);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | 3334.Find the Maximum Factor Score of Array (Solution) | 3334find-the-maximum-factor-score-of-arr-x4vc | 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 | py_nitin | NORMAL | 2024-10-30T05:24:39.552125+00:00 | 2024-10-30T05:24:39.552152+00:00 | 2 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\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```python []\nfrom functools import reduce\ndef gcd(a, b):\n while b:\n a, b = b, a % b\n return a\n\ndef lcm(a, b):\n return a * b // gcd(a, b)\n\ndef array_gcd(nums):\n return reduce(gcd, nums)\n\ndef array_lcm(nums):\n return reduce(lcm, nums)\n\nclass Solution:\n def maxScore(self, nums):\n if len(nums) == 1:\n \n return nums[0] * nums[0]\n \n full_gcd = array_gcd(nums)\n full_lcm = array_lcm(nums)\n max_score = full_gcd * full_lcm \n \n for i in range(len(nums)):\n remaining_nums = nums[:i] + nums[i+1:]\n \n current_gcd = array_gcd(remaining_nums)\n current_lcm = array_lcm(remaining_nums)\n \n current_score = current_gcd * current_lcm\n max_score = max(max_score, current_score)\n \n return max_score\n\nsol = Solution()\nprint(sol.maxScore([2, 4, 8, 16])) \nprint(sol.maxScore([1, 2, 3, 4, 5])) \nprint(sol.maxScore([3])) \n\n``` | 0 | 0 | ['Python'] | 0 |
find-the-maximum-factor-score-of-array | O(n^2) Time complexity. Easy solution✅✅✅. | on2-time-complexity-easy-solution-by-ava-hvt1 | \n\n# Code\njava []\nclass Solution {\n long gcd(long a,long b)\n {\n if(a%b==0)\n {\n return b;\n }\n else\n | avaneesh2523 | NORMAL | 2024-10-30T05:20:12.273448+00:00 | 2024-10-30T05:20:12.273466+00:00 | 9 | false | \n\n# Code\n```java []\nclass Solution {\n long gcd(long a,long b)\n {\n if(a%b==0)\n {\n return b;\n }\n else\n {\n return gcd(b,a%b);\n }\n }\n long calculateLCM(long a,long b)\n {\n return ((a/gcd(a,b))*b);\n }\n public long maxScore(int[] nums) {\n if(nums.length==0)\n {\n return 0;\n }\n else if(nums.length==1)\n {\n return nums[0]*nums[0];\n }\n else\n {\n int[] lcms=new int[nums.length];\n int[] gcds=new int[nums.length];\n for(int i=0;i<nums.length;i++)\n {\n long lcm=i==0?nums[1]:nums[0];\n for(int j=0;j<nums.length;j++)\n {\n if(i!=j && lcm!=nums[j])\n {\n lcm=calculateLCM(lcm,nums[j]);\n }\n }\n lcms[i]=(int)lcm;\n }\n for(int i=0;i<nums.length;i++)\n {\n long g=i==0?nums[1]:nums[0];\n for(int j=0;j<nums.length;j++)\n {\n if(i!=j && g!=nums[j])\n {\n g=gcd(g,nums[j]);\n }\n }\n gcds[i]=(int)g;\n }\n int[] mul=new int[nums.length];\n long max=0;\n for(int i=0;i<lcms.length;i++)\n {\n mul[i]=lcms[i]*gcds[i];\n if(max<mul[i])\n {\n max=mul[i];\n }\n }\n long globallcm=nums[0];\n long globalgcd=nums[0];\n for(int i=1;i<nums.length;i++)\n {\n globallcm=calculateLCM(globallcm,nums[i]);\n globalgcd=gcd(globalgcd,nums[i]);\n }\n long max2=globallcm*globalgcd;\n return Math.max(max,max2);\n }\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-the-maximum-factor-score-of-array | lcm(a,b,c) = lcm(lcm(a,b), c); lcm(a,b) = a*b/gcd(a,b) | lcmabc-lcmlcmab-c-lcmab-abgcdab-by-user5-te6d | rust []\nfn gcd(x: i64, y: i64) -> i64 {\n if y == 0 {x} else {gcd(y, x % y)}\n}\n\nfn lcm(x: i64, y: i64) -> i64 {\n x * y / gcd(x,y) \n}\n\n\nfn cum<I>( | user5285Zn | NORMAL | 2024-10-29T17:13:54.876066+00:00 | 2024-10-29T17:13:54.876102+00:00 | 13 | false | ```rust []\nfn gcd(x: i64, y: i64) -> i64 {\n if y == 0 {x} else {gcd(y, x % y)}\n}\n\nfn lcm(x: i64, y: i64) -> i64 {\n x * y / gcd(x,y) \n}\n\n\nfn cum<I>(xs: I) -> Vec<(i64, i32)> \n where I : Iterator <Item = i32> {\n let mut r = vec![(1, 0)];\n let mut d = 0;\n let mut p = 1;\n for x in xs {\n d = gcd(d as i64, x as i64) as i32;\n p = lcm(p, x as i64);\n r.push((p, d))\n }\n r\n}\n\nimpl Solution {\n pub fn max_score(nums: Vec<i32>) -> i64 {\n if nums.len() == 1 {\n return nums[0] as i64 *nums[0] as i64 ;\n } \n if nums.len() == 2 {\n let x = nums.into_iter().max().unwrap();\n return x as i64 * x as i64 \n }\n\n let a = cum(nums.iter().cloned());\n let b = cum(nums.iter().rev().cloned()).into_iter().rev().skip(1).collect::<Vec<(i64, i32)>>();\n \n let Some(&(p,d)) = a.last() else {panic!()};\n let x = p * d as i64;\n\n \n a.into_iter().zip(b.into_iter()).map(|((p1, d1),(p2, d2))| lcm(p1,p2) * gcd(d1 as i64,d2 as i64)).max().unwrap().max(x)\n \n }\n}\n``` | 0 | 0 | ['Rust'] | 0 |
find-the-maximum-factor-score-of-array | brute force --> better --> optimal ||🧮 || find maximal factor score of array || | brute-force-better-optimal-find-maximal-dz7n8 | 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 | adityamohanty1310 | NORMAL | 2024-10-29T15:16:45.826313+00:00 | 2024-10-29T15:16:45.826348+00:00 | 19 | 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 brute force -- O(N^2)\n optimal -- O(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n O(1)\n\n# Code\n```java []\nclass Solution {\n public long computeGCD(long x, long y) {\n if (y == 0) return x;\n return computeGCD(y, x % y);\n }\n\n public long computeLCM(long x, long y) {\n return (x * y) / computeGCD(x, y);\n }\n\n public long maxScore(int[] numbers) {\n long overallGCD = 0;\n long overallLCM = 1;\n\n for (int number : numbers) {\n overallGCD = computeGCD(overallGCD, number);\n overallLCM = computeLCM(overallLCM, number);\n }\n\n long highestFactorScore = overallGCD * overallLCM;\n\n for (int i = 0; i < numbers.length; i++) {\n long currentGCD = 0;\n long currentLCM = 1;\n\n for (int j = 0; j < numbers.length; j++) {\n if (i != j) {\n currentGCD = computeGCD(currentGCD, numbers[j]);\n currentLCM = computeLCM(currentLCM, numbers[j]);\n }\n }\n\n highestFactorScore = Math.max(highestFactorScore, currentGCD * currentLCM);\n }\n\n return highestFactorScore;\n }\n}\n```\n```java []\nclass Solution {\n public long maxScore(int[] numbers) {\n int length = numbers.length; \n if (length == 1) return (long) numbers[0] * numbers[0];\n \n int[] prefixGCD = new int[length];\n int[] suffixGCD = new int[length];\n long[] prefixLCM = new long[length], suffixLCM = new long[length];\n\n prefixGCD[0] = numbers[0];\n suffixGCD[length - 1] = numbers[length - 1];\n prefixLCM[0] = numbers[0];\n suffixLCM[length - 1] = numbers[length - 1];\n\n for (int i = 1; i < length; i++) {\n prefixGCD[i] = computeGCD(prefixGCD[i - 1], numbers[i]);\n prefixLCM[i] = computeLCM(prefixLCM[i - 1], numbers[i]);\n }\n\n for (int i = length - 2; i >= 0; i--) {\n suffixGCD[i] = computeGCD(suffixGCD[i + 1], numbers[i]);\n suffixLCM[i] = computeLCM(suffixLCM[i + 1], numbers[i]);\n }\n \n long maxScore = (long) prefixGCD[length - 1] * prefixLCM[length - 1];\n \n for (int i = 0; i < length; i++) {\n int currentGCD, currentLCM;\n if (i == 0) {\n currentGCD = suffixGCD[1];\n currentLCM = (int) suffixLCM[1];\n } else if (i == length - 1) {\n currentGCD = prefixGCD[length - 2];\n currentLCM = (int) prefixLCM[length - 2];\n } else {\n currentGCD = computeGCD(prefixGCD[i - 1], suffixGCD[i + 1]);\n currentLCM = (int) computeLCM(prefixLCM[i - 1], suffixLCM[i + 1]);\n }\n maxScore = Math.max(maxScore, (long) currentGCD * currentLCM);\n }\n return maxScore;\n }\n\n private long computeLCM(long a, long b) {\n return (a / computeGCD(a, b)) * b;\n }\n\n private int computeGCD(long a, long b) {\n while (b != 0) {\n long temp = a % b;\n a = b;\n b = temp;\n }\n return (int) a;\n }\n}\n\n``` | 0 | 0 | ['Array', 'Math', 'Suffix Array', 'Number Theory', 'Prefix Sum', 'Java'] | 0 |
find-the-maximum-factor-score-of-array | Solved by Relation between gcd and lcm , C++ , TC : O ( n^2 ) ,SC: O ( 1 ) | solved-by-relation-between-gcd-and-lcm-c-vk0x | 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 | Devarshi1206 | NORMAL | 2024-10-29T15:13:03.329916+00:00 | 2024-10-29T15:13:03.329951+00:00 | 14 | 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```cpp []\nclass Solution {\npublic:\n#define ll long long\n ll fact(vector<int>& n,int indskip){\n ll gcd =0;\n ll lcm =1;\n for(int i=0;i<n.size();i++){\n if(indskip==i) continue;\n gcd=__gcd(gcd ,(ll)n[i] );\n lcm=(n[i]*lcm)/__gcd((ll)n[i],lcm);\n }\n return gcd*lcm;\n }\n long long maxScore(vector<int>& n) {\n if(n.size()==1) return n[0]*n[0];\n ll ans = fact(n,-1);\n for(int i=0;i<n.size();i++){\n ans = max(ans, fact(n,i));\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | Step-by-Step Solution | step-by-step-solution-by-lakshy01-lbi9 | Intuition\n Describe your first thoughts on how to solve this problem. \n\nYou\u2019re given a list of numbers, and your mission (should you choose to accept it | lakshy01 | NORMAL | 2024-10-29T14:45:34.669210+00:00 | 2024-10-29T14:45:34.669240+00:00 | 10 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nYou\u2019re given a list of numbers, and your mission (should you choose to accept it) is to calculate the maximum score by playing around with the GCD (Greatest Common Divisor) and LCM (Least Common Multiple) of these numbers.\n\nSo, imagine you\u2019re handed a few numbers on a piece of paper. Your goal is to create the highest score possible by performing some clever calculations. What you\u2019re going to do is:\n\n1. For every number, calculate the GCD and LCM in a way that considers that number and all the numbers after it in the list.\n2. Find the combination that gives you the maximum value when you multiply the LCM and GCD of a sub-list.\n3. And voil\xE0, that\u2019s your answer!\n\nThe code tries to perform these calculations efficiently, because who wants to spend too long crunching numbers?\n\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. Helper Functions:\n - gcd(a, b): This function calculates the greatest common divisor using recursion.\n - lcm(a, b): This function calculates the least common multiple using the GCD function.\n\n2. Calculate GCD and LCM Arrays:\n - We start by creating two vectors (gcdNums and lcmNums) to store the cumulative GCD and LCM from each index to the end.\n - We fill gcdNums and lcmNums starting from the end of the nums list.\n\n3. Maximizing the Score:\n\n - We initialize a result res using the product of the full list\'s LCM and GCD from the first element.\n - We then iterate through the list:\n - At each index, we try removing the element at that position and calculate the LCM and GCD of the remaining elements.\n - If the calculated product is higher than res, we update res.\n - Finally, we return the maximum score found.\n\n# Step-by-Step\n\nImagine your list as a series of elements:\n\n- Start with calculating the GCD and LCM arrays, filling them from the end to the start:\n\n```ruby []\nnums: [a, b, c, d, e]\ngcdNums: [GCD(a, b, c, d, e), GCD(b, c, d, e), ..., GCD(e)]\nlcmNums: [LCM(a, b, c, d, e), LCM(b, c, d, e), ..., LCM(e)]\n```\n\n- For each element i in nums, calculate the maximum possible res by removing element i and taking the product of the GCD and LCM of the remaining elements. For example:\n\n```ruby []\nRemove a:\n GCD(b, c, d, e) * LCM(b, c, d, e)\n```\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\nThe overall time complexity is \n`\uD835\uDC42(\uD835\uDC5B)`\nwhere n is the length of nums. Calculating GCD and LCM for each pair takes constant time (in practice), and filling up gcdNums and lcmNums takes linear time since we only calculate each once.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\nWe\u2019re using additional arrays gcdNums and lcmNums of size \n`\uD835\uDC42(\uD835\uDC5B)` to store cumulative values. So, the space complexity is \n`\uD835\uDC42(\uD835\uDC5B)`.\n\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long gcd(long long a, long long b) {\n if(b == 0) return a;\n return gcd(b, a % b);\n }\n\n long long lcm(long long a, long long b) {\n return (a / gcd(a, b)) * b;\n }\n\n long long maxScore(vector<int>& nums) {\n int n = nums.size();\n vector<long long> gcdNums(n), lcmNums(n);\n gcdNums[n - 1] = nums[n - 1];\n lcmNums[n - 1] = nums[n - 1];\n for(int i = n - 2; i >= 0; i--) {\n lcmNums[i] = lcm(nums[i], lcmNums[i + 1]);\n gcdNums[i] = gcd(nums[i], gcdNums[i + 1]);\n }\n long long res = lcmNums[0] * gcdNums[0];\n long long cLcm = nums[0], cGcd = nums[0];\n for(int i = 0; i < n - 1; ++i) {\n // remove the element\n if(i == 0) res = max(res, lcmNums[i + 1] * gcdNums[i + 1]);\n else res = max(res, lcm(cLcm, lcmNums[i + 1]) * gcd(cGcd, gcdNums[i + 1]));\n cLcm = lcm(cLcm, nums[i]);\n cGcd = gcd(cGcd, nums[i]);\n }\n res = max(res, cLcm * cGcd);\n return res;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | Maximizing Array Products with Prefix and Suffix GCD-LCM in C++ | maximizing-array-products-with-prefix-an-lkjm | Intuition\nThe problem requires maximizing a product involving the GCD and LCM of subarrays. By separating the array into different prefix and suffix segments, | krishnavipulcoder | NORMAL | 2024-10-29T13:37:46.003877+00:00 | 2024-10-29T13:37:46.003920+00:00 | 15 | false | # Intuition\nThe problem requires maximizing a product involving the **GCD** and **LCM **of subarrays. By separating the array into different **prefix **and **suffix **segments, we can efficiently calculate the maximum possible GCD-LCM product using precomputed arrays.\n\n# Approach\n# 1. Precompute Prefix and Suffix Arrays:\nCompute prefix GCDs (gcd_left) and suffix GCDs (gcd_right) for every index to get the GCD of all elements to the left and right.\nSimilarly, compute prefix LCMs (lcm_left) and suffix LCMs (lcm_right) for all elements.\n\n# 2. Calculate Maximum Product:\nInitialize the answer by considering products at the edges of the array.\nFor each element, compute the maximum GCD-LCM product by excluding the element at index i and combining the left and right segments.\n\n## 3. Return Result: Return the highest product found.\n\n# Complexity\n- Time complexity:\n O(n) as we only make linear passes through the array to compute prefix and suffix GCDs and LCMs.\n\n- Space complexity:\nO(n), for storing the prefix and suffix arrays (gcd_left, gcd_right, lcm_left, lcm_right).\n\n \n\n# Code\n```cpp []\nclass Solution {\npublic:\n // Function to calculate LCM of two numbers\n long long lcm(long a ,long b) {\n return (a / gcd(a, b)) * b;\n }\n \n long long maxScore(vector<int>& nums) { \n int n = nums.size();\n \n // Edge case: If there\'s only one element, return its square\n if (n == 1)\n return nums[0] * nums[0];\n\n // Prefix and suffix arrays to store GCDs and LCMs\n vector<long long> gcd_left(n);\n vector<long long> gcd_right(n);\n gcd_left[0] = nums[0];\n\n // Calculate prefix GCDs\n for (int i = 1; i < n; i++) {\n gcd_left[i] = gcd(gcd_left[i - 1], nums[i]);\n }\n\n gcd_right[n - 1] = nums[n - 1];\n\n // Calculate suffix GCDs\n for (int i = n - 2; i >= 0; i--) {\n gcd_right[i] = gcd(gcd_right[i + 1], nums[i]);\n }\n\n // Prefix and suffix arrays to store LCMs\n vector<long long> lcm_left(n);\n vector<long long> lcm_right(n);\n lcm_left[0] = nums[0];\n\n // Calculate prefix LCMs\n for (int i = 1; i < n; i++) {\n lcm_left[i] = lcm(lcm_left[i - 1], nums[i]);\n }\n\n lcm_right[n - 1] = nums[n - 1];\n\n // Calculate suffix LCMs\n for (int i = n - 2; i >= 0; i--) {\n lcm_right[i] = lcm(lcm_right[i + 1], nums[i]);\n }\n \n // Initialize answer with max product from edges\n long long ans = max({gcd_right[1] * lcm_right[1], lcm_left[n - 2] * gcd_left[n - 2]});\n\n // Calculate maximum product by checking all subarrays\n for (int i = 1; i < n - 1; i++) {\n long long a = gcd(gcd_left[i - 1], gcd_right[i + 1]);\n long long b = lcm(lcm_left[i - 1], lcm_right[i + 1]);\n ans = max(ans, a * b);\n }\n\n // Check the final possible combination\n long long res = lcm_left[n - 1] * gcd_left[n - 1];\n ans = max(ans, res);\n \n return ans;\n }\n};\n\n``` | 0 | 0 | ['Suffix Array', 'C++'] | 0 |
find-the-maximum-factor-score-of-array | C++ Code with complexity O(n^2) and O(1) | c-code-with-complexity-on2-and-o1-by-hit-fhja | 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 | hitkar_miglani | NORMAL | 2024-10-29T11:17:20.674241+00:00 | 2024-10-29T11:17:20.674266+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: O(n^2)\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```cpp []\n#include<algorithm>\nclass Solution {\npublic:\n long long maxScore(vector<int>& nums) {\n int n = nums.size();\n long long result = 0;\n for(int i = -1;i<n;i++){\n long long lcm=1,gcd=0;\n for(int j = 0;j<n;j++){\n if(i==j) continue;\n gcd = __gcd(gcd,(long long)nums[j]);\n lcm = (lcm*nums[j])/__gcd(lcm,(long long)nums[j]); \n }\n\n result = max(result,lcm*gcd);\n }\n return result;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | [Python] 5 lines simple brute force | python-5-lines-simple-brute-force-by-pbe-dw6v | \nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n m = lcm(*nums)*gcd(*nums)\n\n for i in range(len(nums)):\n a = num | pbelskiy | NORMAL | 2024-10-29T10:08:36.200063+00:00 | 2024-10-29T10:08:36.200099+00:00 | 13 | false | ```\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n m = lcm(*nums)*gcd(*nums)\n\n for i in range(len(nums)):\n a = nums[:i] + nums[i+1:]\n m = max(m, lcm(*a)*gcd(*a))\n \n return m\n``` | 0 | 0 | ['Math', 'Python'] | 0 |
find-the-maximum-factor-score-of-array | Just Brute Force it !! | just-brute-force-it-by-mr-banana-q15z | 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 | kr-ankit | NORMAL | 2024-10-29T04:32:22.879238+00:00 | 2024-10-29T04:32:22.879275+00:00 | 12 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:$$O(n^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 long long lcm_cal(vector<int>temp){\n if(temp.size()==0)return 0;\n long long ans=temp[0];\n for(int i=0;i<temp.size();i++)ans=lcm(ans,temp[i]);\n return ans;\n }\n long long gcd_cal(vector<int>temp){\n if(temp.size()==0)return 0;\n long long ans=temp[0];\n for(int i=0;i<temp.size();i++)ans=gcd(ans,temp[i]);\n return ans;\n }\n long long maxScore(vector<int>& nums) {\n long long factor_score=lcm_cal(nums)*(gcd_cal(nums));\n for(int i=0;i<nums.size();i++){\n vector<int>temp;\n for(int j=0;j<i;j++)temp.push_back(nums[j]);\n for(int k=i+1;k<nums.size();k++)temp.push_back(nums[k]);\n factor_score=max(factor_score,(lcm_cal(temp)*(gcd_cal(temp))));\n }\n return factor_score;\n }\n};\n``` | 0 | 0 | ['Array', 'Math', 'Number Theory', 'C++'] | 0 |
find-the-maximum-factor-score-of-array | C++ | Prefix Suffix | c-prefix-suffix-by-pikachuu-euhg | Code\ncpp []\nclass Solution {\npublic:\n long long maxScore(vector<int>& nums) {\n int n = nums.size();\n if(n == 1) return nums[0] * nums[0]; | pikachuu | NORMAL | 2024-10-28T21:10:26.994917+00:00 | 2024-10-28T21:10:26.994945+00:00 | 8 | false | # Code\n```cpp []\nclass Solution {\npublic:\n long long maxScore(vector<int>& nums) {\n int n = nums.size();\n if(n == 1) return nums[0] * nums[0];\n vector<long long> gcdRight(n), lcmRight(n);\n gcdRight[n - 1] = lcmRight[n - 1] = nums[n - 1];\n long long ans = 0;\n for(int i = n - 2; i >= 0; i--) {\n gcdRight[i] = gcd(gcdRight[i + 1], nums[i]);\n lcmRight[i] = lcm(lcmRight[i + 1], nums[i]);\n }\n long long gcdLeft = nums[0], lcmLeft = nums[0];\n for(int i = 1; i < n - 1; i++) {\n long long g = gcd(gcdLeft, gcdRight[i + 1]);\n long long l = lcm(lcmLeft, lcmRight[i + 1]);\n gcdLeft = gcd(gcdLeft, nums[i]);\n lcmLeft = (lcmLeft * nums[i]) / gcd(lcmLeft, nums[i]);\n ans = max(ans, l * g);\n }\n // Remove leftmost\n ans = max(ans, gcdRight[1] * lcmRight[1]);\n // Remove none\n ans = max(ans, gcdRight[0] * lcmRight[0]);\n // Remove rightmost\n ans = max(ans, gcdLeft * lcmLeft);\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | Python || Simple solution | python-simple-solution-by-vilaparthibhas-t8hl | 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 | vilaparthibhaskar | NORMAL | 2024-10-28T18:57:59.873670+00:00 | 2024-10-28T18:57:59.873689+00:00 | 3 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n \n def lcm(a, b):\n return a * b // math.gcd(a, b)\n \n def gcd(a, b):\n return math.gcd(a, b)\n \n def factor(ar):\n if len(ar) == 0:return 0\n lm = reduce(lcm, ar)\n gd = reduce(gcd, ar)\n return lm * gd\n \n mx = factor(nums)\n for i in range(len(nums)):\n ar = nums[:i] + nums[i + 1:]\n mx = max(mx, factor(ar))\n return mx\n \n``` | 0 | 0 | ['Math', 'Python3'] | 0 |
find-the-maximum-factor-score-of-array | Java | DP | time O(N) | Beats 100.00% | java-dp-time-on-beats-10000-by-markchen8-klin | Intuition\n Describe your first thoughts on how to solve this problem. \nif we want to calculate the factor score which removed nums[i],\nwe need prefix[i-1] an | markchen83115 | NORMAL | 2024-10-28T15:00:54.405542+00:00 | 2024-10-29T08:59:15.204006+00:00 | 19 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nif we want to calculate the **factor score** which removed `nums[i]`,\nwe need `prefix[i-1]` and `suffix[i+1]`\n```text\nprefix[i-1] suffix[i+1]\n[x x x x] x [x x x x]\n i \n```\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. calculate all `prefix[i]` for GCD and LCM\n2. go backward to calculate `suffix[i]` for GCD and LCM\n3. update the max **factor score** at the same time\n\ntips:\n`gcd(0, k) = k`\n`lcm(1, k) = k`\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public long maxScore(int[] nums) {\n int n = nums.length;\n long[] prefixGCD = new long[n];\n long[] prefixLCM = new long[n];\n prefixGCD[0] = nums[0];\n prefixLCM[0] = nums[0];\n\n // 1. calculate all prefix[i] for GCD and LCM\n for (int i = 1; i < n; i++)\n {\n prefixGCD[i] = gcd(prefixGCD[i - 1], nums[i]);\n prefixLCM[i] = lcm(prefixLCM[i - 1], nums[i]);\n }\n long ret = prefixGCD[n - 1] * prefixLCM[n - 1]; // select all elements\n\n // 2. go backward to calculate suffix[i] for GCD and LCM\n // 3. update the max factor score at the same time\n long suffixGCD = 0;\n long suffixLCM = 1;\n for (int i = n - 1; i >= 1; i--)\n {\n // remove one element\n long score = lcm(prefixLCM[i - 1], suffixLCM) * gcd(prefixGCD[i - 1], suffixGCD);\n ret = Math.max(ret, score);\n\n suffixGCD = gcd(suffixGCD, nums[i]);\n suffixLCM = lcm(suffixLCM, nums[i]);\n }\n ret = Math.max(ret, suffixGCD * suffixLCM);\n\n return ret;\n }\n\n long gcd(long a, long b)\n {\n return b == 0 ? a : gcd(b, a % b);\n }\n\n long lcm(long a, long b)\n {\n return a * b / gcd(a, b);\n }\n}\n``` | 0 | 0 | ['Java'] | 0 |
find-the-maximum-factor-score-of-array | Python: Beats 100% | python-beats-100-by-alexc2024-nx0m | Intuition\nCreate functions for lcn(nums) and gcd(nums), calculate the maxfactor. Try removing the numbers one by one from the list and check whether the update | AlexC2024 | NORMAL | 2024-10-28T12:45:14.926693+00:00 | 2024-10-28T12:45:14.926725+00:00 | 30 | false | # Intuition\nCreate functions for lcn(nums) and gcd(nums), calculate the maxfactor. Try removing the numbers one by one from the list and check whether the updated maxfactor exceeds the running maximum\n\n# Approach\nThe idea is to convert the list of numbers into a matrix of size 11xn, where each row will contain the powers of each number from the list corresponding to a prime number under 30. nRows = 11 because there are 11 prime numbers under 30. Then for gcd we need to take the minimums for each row, and for lcn the maximums. After that we raise the prime numbers into these powers and multiply together. Removing one original number from the list is the same as removing one column from the grand matrix and recalculating the mins/maxs and gcd/lcn.\n\n# Complexity\n- Time complexity:\nBeats 100%\n\n- Space complexity:\nBeats 100%\n\n# Code\n```python []\nclass Solution(object):\n def gcd(self, pows, prime_numbers):\n result = 1\n for ipow, powstr in enumerate(pows):\n minpow = min(powstr)\n result*=(prime_numbers[ipow]**minpow)\n return result\n\n def lcn(self, pows, prime_numbers):\n result = 1\n for ipow, powstr in enumerate(pows):\n maxpow = max(powstr)\n result*=(prime_numbers[ipow]**maxpow)\n return result\n\n def maxScore(self, nums):\n """\n :type nums: List[int]\n :rtype: int\n """\n prime_numbers = [2,3,5,7,11,13,17,19,23,29]\n pows = [[] for i in range(len(prime_numbers))]\n if len(nums)==1:\n return nums[0]*nums[0] \n for i_prime in range(len(prime_numbers)):\n for num_i in nums:\n power = 0\n while num_i % prime_numbers[i_prime]==0:\n num_i/=prime_numbers[i_prime]\n power+=1\n pows[i_prime].append(power)\n maxfactor = self.gcd(pows, prime_numbers)*self.lcn(pows, prime_numbers)\n for inum in range(len(nums)):\n new_pows = [pows_i[:] for pows_i in pows]\n for new_pows_i in new_pows:\n new_pows_i.pop(inum)\n new_factor = self.gcd(new_pows, prime_numbers)*self.lcn(new_pows, prime_numbers)\n if new_factor>maxfactor:\n maxfactor = new_factor\n return maxfactor\n\n``` | 0 | 0 | ['Python'] | 1 |
find-the-maximum-factor-score-of-array | Easiest || C++ || Beginer Friendly 🏆 | easiest-c-beginer-friendly-by-gupta14ayn-uv7p | Intuition\n Describe your first thoughts on how to solve this problem. \nThe factor score is the product of LCM and GCD of the elements in the array. Removing d | gupta14aynat | NORMAL | 2024-10-28T11:51:48.898220+00:00 | 2024-10-28T11:51:48.898244+00:00 | 20 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe factor score is the product of LCM and GCD of the elements in the array. Removing different elements will change the LCM and GCD, so we need to check each possibility to find the maximum score.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Calculate LCM and GCD: For the entire array, compute the LCM and GCD.\n2. Remove Each Element: For each element in the array, compute the LCM and GCD of the remaining elements.\n3. Maximize Factor Score: Calculate the factor score for each configuration and track the maximum score found.\n4. Return the Result: Finally, return the highest factor score.\n\n# Complexity\n- Time complexity:\uD835\uDC42(n^2)\nWe loop through each element (to remove it) and then loop through the rest to calculate LCM and GCD, resulting in quadratic time complexity.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long lhlp(vector<int>nums, int x){\n long long ans =-1;\n for(int i=0;i<nums.size();i++){\n if(i == x)continue;\n if(ans == -1)ans = nums[i];\n else ans = (ans*nums[i])/gcd(static_cast<long long>(ans),static_cast<long long>(nums[i]));\n }\n return ans;\n }\n int ghlp(vector<int>nums, int x){\n int ans = -1;\n for(int i=0;i<nums.size();i++){\n if(i ==x)continue;\n if(ans == -1)ans = nums[i];\n else\n ans = gcd(ans,nums[i]);\n if(ans ==1)break;\n }\n return ans;\n }\n long long maxScore(vector<int>& nums) {\n int n = nums.size();\n //fs = lcm * gcd of all n elem\n // return max(fs) --> remove 1 elem from it \n //if n == 0 fs =0;\n if(n ==0 )return 0;\n if(n ==1)return nums[0]*nums[0];\n sort(nums.begin(), nums.end());\n long long fs = lhlp(nums,-1)*ghlp(nums,-1);\n for(int i=0;i<nums.size();i++){\n long long l1 = lhlp(nums,i);\n int g1 = ghlp(nums,i);\n long long f2 = l1*g1;\n fs = max(fs, f2);\n }\n return fs;\n }\n};\n\n\n\n\n//4 20 4 6 15\n//4 4 6 15 20\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | C++ solution prefix + suffix array | c-solution-prefix-suffix-array-by-oleksa-axgg | \n// Please, upvote if you like it. Thanks :-)\nlong long maxScore(vector<int>& nums) {\n\tint n = nums.size();\n\tif (n == 1)\n\t\treturn nums.back() * nums.ba | oleksam | NORMAL | 2024-10-28T09:22:04.471979+00:00 | 2024-10-28T09:22:04.472017+00:00 | 10 | false | ```\n// Please, upvote if you like it. Thanks :-)\nlong long maxScore(vector<int>& nums) {\n\tint n = nums.size();\n\tif (n == 1)\n\t\treturn nums.back() * nums.back();\n\tvector<long long> pregcd(n, nums[0]), prelcm(n, nums[0]);\n\tvector<long long> postgcd(n, nums.back()), postlcm(n, nums.back());\n\tfor (int i = 1; i < n; i++) {\n\t\tpregcd[i] = __gcd(pregcd[i - 1], 1LL * nums[i]);\n\t\tprelcm[i] = lcm(prelcm[i - 1], 1LL * nums[i]);\n\t}\n\tfor (int i = n - 2; i >= 0; i--) {\n\t\tpostgcd[i] = __gcd(postgcd[i + 1], 1LL * nums[i]);\n\t\tpostlcm[i] = lcm(postlcm[i + 1], 1LL * nums[i]);\n\t}\n\tlong long res = max( { pregcd.back() * prelcm.back(),\n\t\t\t\t\t\t pregcd[n - 2] * prelcm[n - 2],\n\t\t\t\t\t\t postgcd[1] * postlcm[1] } );\n\tfor (int i = 1; i + 1 < n; i++) {\n\t\tres = max(res, __gcd(pregcd[i - 1], postgcd[i + 1]) *\n\t\t\t\t\t lcm(prelcm[i - 1], postlcm[i + 1]));\n\t}\n\treturn res;\n}\n``` | 0 | 0 | ['Array', 'Math', 'Greedy', 'C', 'C++'] | 0 |
find-the-maximum-factor-score-of-array | My solution | my-solution-by-sahil-2005-0khq | 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 | Sahil-2005 | NORMAL | 2024-10-28T09:14:28.075262+00:00 | 2024-10-28T09:14:28.075293+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```cpp []\nclass Solution {\npublic:\n // function to calculate the score using lcm and gcd array\n long long scoreCalculate(vector<int>&a,vector<int>&b,unordered_set<int>&st,unordered_map<int,int>&mp){\n long long ans=1;\n for(int ele:st){\n ans*=pow(ele,a[mp[ele]]+b[mp[ele]]);\n }\n return ans;\n }\n\n long long maxScore(vector<int>& nums) {\n int n=nums.size();\n if(n==1)return nums[0]*nums[0];\n // count array to count the frequency of each element \n vector<int>count(31,0);\n // set containing all prime number under 30\n unordered_set<int>pri={2,3,5,7,11,13,17,19,23,29};\n // map to get index corresponding to each prime no.\n unordered_map<int,int>prime={{2,0},{3,1},{5,2},{7,3},{11,4},{13,5},{17,6},{19,7},{23,8},{29,9}};\n \n int k=0;//denotes no. of prime numbers\n\n\n // 1<=nums[i]<=30 so we prime factorise all nums[i] and store prime factorization of each element \n // to store we use vector in which index enotes the prime no. (can be found using map declared above) and value at index denotes the count of that prime no. in prime factorization of nums[i]\n // to LCM just find max count of each prime no. for all nums[i]\n // to get GCD just take intersection/common of count of each prime no. for all element\n // effect of removing 1 element gcd ---> can increase or remain same\n // lcm ----> can decrease or remain same\n // so if removing 1 element does not increase gcd then their is no point in deleting it\n\n\n // array to store prime number factorization of array\n vector<vector<int>>factor(31,vector<int>(10,0));\n // array to store the maximum count of each prime no. inorder to get LCM\n vector<int>lcm(10,0);\n // array to store the minmum count of each prime no. inorder to get GCD\n vector<int>gcd(10,0);\n\n // by default gcd has all 0 so if we take minimum it will give 0\n // but we want common in all no. ---> first take 1st number then start taking common using it\n\n // bool variable to denote whether 1st element is taken or not\n bool first=false;\n\n // iterate over all element\n for(int i=0;i<n;i++){\n // increse the count of nums[i]\n count[nums[i]]++;\n\n // don\'t calculate the effect of 1; \n // as if no. of 1 =1 then delete this 1 and calculate score is our answer\n // and if no. of 1>1 then gcd=1 and don\'t remove any element and calculate lcm give us our answer\n // if count[nums[i]]>1 means we have already prime factorise nums[i] and nums[i] effect on gcd and lcm has been taken under concentration\n if(nums[i]==1 || count[nums[i]]>1){\n continue;\n }else if(pri.count(nums[i])){\n // if number if prime \n factor[nums[i]][prime[nums[i]]]++;\n k++; // inc the count of prime no.\n }else{\n // factorise nums[i] and store \n for(int ele:pri){\n int temp=nums[i];\n while(temp%ele==0){\n factor[nums[i]][prime[ele]]++;\n temp/=ele;\n }\n }\n }\n if(!first){\n // if nums[i] is the first no. \n for(int ele:pri){\n lcm[prime[ele]]=factor[nums[i]][prime[ele]];\n gcd[prime[ele]]=factor[nums[i]][prime[ele]];\n }\n first=true;\n }else{\n // calculate maximum and minimun count\n for(int ele:pri){\n lcm[prime[ele]]=max(lcm[prime[ele]],factor[nums[i]][prime[ele]]);\n gcd[prime[ele]]=min(gcd[prime[ele]],factor[nums[i]][prime[ele]]);\n }\n } \n }\n // calculate score \n long long score=scoreCalculate(lcm,gcd,pri,prime);\n if(count[1]==1){\n // if count of 1 is 1 means then removing it will not decrese LCm but it can incrase gcd so it is the ideal choice for removing\n return score;\n }else if(count[1]>1 || k>2){\n // if no. of 1 >1 or no. of prime no. >2 then even after removing 1 element gcd stil remain 1 don/t delete any element and calculate answer \n score=1;\n for(int ele:pri){\n score*=pow(ele,lcm[prime[ele]]);\n }\n return score;\n }\n \n for(int k=2;k<31;k++){\n // if count of k>1 then removing it has no. impact on lcm and gcd so don\'t check this case\n \n // check if we delete k what will be the lcm and gcd\n if(count[k]==1){\n // empty the lcm and gcd array\n for(int i=0;i<10;i++){\n lcm[i]=gcd[i]=0;\n }\n first=false;// initalaise the first \n for(int i=2;i<31;i++){\n if(k==i || count[i]==0)continue;\n if(!first){\n for(int ele:pri){\n lcm[prime[ele]]=factor[i][prime[ele]];\n gcd[prime[ele]]=factor[i][prime[ele]];\n }\n first=true;\n }else{\n for(int ele:pri){\n lcm[prime[ele]]=max(lcm[prime[ele]],factor[i][prime[ele]]);\n gcd[prime[ele]]=min(gcd[prime[ele]],factor[i][prime[ele]]);\n }\n } \n }\n\n long long temp=scoreCalculate(lcm,gcd,pri,prime);\n if(score<temp)score=temp;\n }\n }\n return score;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | My Solution | my-solution-by-hope_ma-kmw7 | \n/**\n * Time Complexity: O(n)\n * Space Complexity: O(n)\n * where `n` is the length of the vector `nums`\n */\nclass Solution {\n public:\n long long maxSco | hope_ma | NORMAL | 2024-10-28T05:40:38.665618+00:00 | 2024-10-28T05:40:38.665644+00:00 | 0 | false | ```\n/**\n * Time Complexity: O(n)\n * Space Complexity: O(n)\n * where `n` is the length of the vector `nums`\n */\nclass Solution {\n public:\n long long maxScore(const vector<int> &nums) {\n const int n = static_cast<int>(nums.size());\n long long left_gcd[n];\n memset(left_gcd, 0, sizeof(left_gcd));\n left_gcd[0] = nums.front();\n long long left_lcm[n];\n memset(left_lcm, 0, sizeof(left_lcm));\n left_lcm[0] = nums.front();\n \n for (int i = 1; i < n; ++i) {\n left_gcd[i] = get_gcd(left_gcd[i - 1], nums[i]);\n left_lcm[i] = get_lcm(left_lcm[i - 1], nums[i]);\n }\n \n long long ret = left_gcd[n - 1] * left_lcm[n - 1];\n long long right_gcd = 0;\n long long right_lcm = 1;\n for (int i = n - 1; i > 0; --i) {\n ret = max(ret, get_gcd(left_gcd[i - 1], right_gcd) * get_lcm(left_lcm[i - 1], right_lcm));\n right_gcd = get_gcd(right_gcd, nums[i]);\n right_lcm = get_lcm(right_lcm, nums[i]);\n }\n ret = max(ret, right_gcd * right_lcm);\n return ret;\n }\n \n private:\n long long get_gcd(const long long a, const long long b) {\n if (a == 0) {\n return b;\n }\n return get_gcd(b % a, a);\n }\n \n long long get_lcm(const long long a, const long long b) {\n const long long gcd = get_gcd(a, b);\n return (a / gcd) * b;\n }\n};\n``` | 0 | 0 | [] | 0 |
find-the-maximum-factor-score-of-array | precompute prefix and suffix lcm's and gcd's | Python | precompute-prefix-and-suffix-lcms-and-gc-1ooh | \n"""\nPrecompute the prefix and suffix lcm\'s and gcd\'s.\n"""\n\nfrom math import gcd, lcm\nclass Solution:\n def maxScore(self, A: List[int]) -> int:\n | wxy0925 | NORMAL | 2024-10-28T04:12:29.858499+00:00 | 2024-10-28T04:12:29.858536+00:00 | 11 | false | ```\n"""\nPrecompute the prefix and suffix lcm\'s and gcd\'s.\n"""\n\nfrom math import gcd, lcm\nclass Solution:\n def maxScore(self, A: List[int]) -> int:\n n = len(A)\n \n if n == 1:\n return A[0] ** 2\n \n gcd_left = [1] * n\n gcd_right = [1] * n\n lcm_left = [1] * n\n lcm_right = [1] * n\n \n gcd_left[0] = A[0]\n lcm_left[0] = A[0]\n gcd_right[n-1] = A[n-1]\n lcm_right[n-1] = A[n-1]\n \n for i in range(1, n):\n gcd_left[i] = gcd(gcd_left[i-1], A[i])\n lcm_left[i] = lcm(lcm_left[i-1], A[i])\n \n for i in range(n-2, -1, -1):\n gcd_right[i] = gcd(A[i], gcd_right[i+1])\n lcm_right[i] = lcm(A[i], lcm_right[i+1])\n \n \n # print(f"{gcd_left=}")\n # print(f"{lcm_left=}")\n # print(f"{gcd_right=}")\n # print(f"{lcm_right=}")\n \n score = gcd_left[-1] * lcm_left[-1]\n \n for i in range(n):\n if i == 0:\n factor = gcd_right[i+1]\n multiple = lcm_right[i+1]\n \n elif i == n - 1:\n factor = gcd_left[i-1]\n multiple = lcm_left[i-1]\n \n else:\n factor = gcd(gcd_left[i-1], gcd_right[i+1])\n \n lcm_left_to_i = lcm_left[i-1]\n lcm_right_to_i = lcm_right[i+1]\n \n multiple = lcm(lcm_left_to_i, lcm_right_to_i)\n \n \n score = max(score, factor * multiple)\n \n return score\n \n``` | 0 | 0 | ['Python'] | 0 |
find-the-maximum-factor-score-of-array | Maximum Factor Score After Removing At Most One Element | maximum-factor-score-after-removing-at-m-u389 | Intuition\nWhen I first saw this problem, I realized we need to calculate the (GCD \times LCM) for different subarrays after removing at most one element. The k | iammawaistariq | NORMAL | 2024-10-28T02:09:33.962836+00:00 | 2024-10-28T02:09:33.962866+00:00 | 9 | false | # Intuition\nWhen I first saw this problem, I realized we need to calculate the $$(GCD \\times LCM)$$ for different subarrays after removing at most one element. The key insight is that we need to compare the factor score of the original array with the scores after removing each element one by one to find the maximum possible score.\n\n\n# Approach\n1. First, create helper functions for calculating:\n - LCM of two numbers using the formula: LCM = (a*b)/GCD\n - GCD of array using reduce function\n - LCM of array using reduce function\n - Factor score (GCD * LCM) for an array\n\n2. In the main function:\n - Handle the base case (single element array) where factor score is number.\n - Calculate initial factor score without removing any element\n - For each element in array:\n - Create a new array excluding that element\n - Calculate its factor score\n - Update maximum score if current score is higher\n - Return the maximum score found\n\n# Complexity\n- **Time complexity:**\n - $$O(n^2 \\log m)$$ where $$n$$ is the length of array and m is the maximum number in array.\n - We try removing each element: $$O(n)$$\n - For each removal, we calculate GCD and LCM of remaining elements: $$O(n log m)$$\n\n- **Space complexity:**\n - $$O(n)$$ to store new arrays when removing elements\n\n# Code\n```python3 []\nfrom math import gcd\nfrom functools import reduce\n\nclass Solution:\n def maxScore(self, nums: List[int]) -> int:\n\n def lcm(a, b):\n return abs(a * b) // gcd(a, b)\n \n def array_gcd(arr):\n return reduce(gcd, arr)\n \n def array_lcm(arr):\n return reduce(lcm, arr)\n \n def get_factor_score(arr):\n if not arr:\n return 0\n if len(arr) == 1:\n return arr[0] * arr[0]\n return array_gcd(arr) * array_lcm(arr)\n \n n = len(nums)\n if n == 1:\n return nums[0] * nums[0]\n \n # Try removing each element and calculate factor score\n max_score = get_factor_score(nums) # Score without removing any element\n \n for i in range(n):\n # Create new array without element at index i\n new_nums = nums[:i] + nums[i+1:]\n score = get_factor_score(new_nums)\n max_score = max(max_score, score)\n \n return max_score\n``` | 0 | 0 | ['Python3'] | 0 |
find-the-maximum-factor-score-of-array | Greedy Algorithm | greedy-algorithm-by-alanchanghsnu-af3b | Approach\n1. len = 1\n\nWe can get the result num[0]^2\n\n2. len = 2\n\nAssume [a*b, a*c] where LCM = a, GCD = a*b*c. Then res = a*a*b*c = (a*b) * (a*c).\nIf we | alanchanghsnu | NORMAL | 2024-10-27T21:39:30.842480+00:00 | 2024-10-27T21:50:10.234991+00:00 | 18 | false | # Approach\n1. `len = 1`\n\nWe can get the result `num[0]^2`\n\n2. `len = 2`\n\nAssume `[a*b, a*c]` where `LCM = a`, `GCD = a*b*c`. Then `res = a*a*b*c = (a*b) * (a*c)`.\nIf we choose to remove smaller one `(a*b)`, then `res = (a*c) * (a*c)` .\n\nSince `a*b < a*c`, we can know that the best strategy is to remove the smaller num.\n\n3. `len >= 3`\n\nAssume it is sorted array `[abce, abdf, acdg] (bce <= bdf <= cdg)`\n\n a. If no remove: `LCM = a, GCD = abcdefg -> res = aabcdefg`\n b. If remove `abce`: `LCM = ad, GCD = abcdfg -> res = aabcddfg`\n c. If remove `abdf`: `LCM = ac, GCD = abcdeg -> res = aabccdeg`\n d. If remove `acdg`: `LCM = ab, GCD = abcdef -> res = aabbcdef`\n\nFrom the above comparison, we can see it is difficult to identify which result will give the max value. Hence simply greedy algorithm doesn\'t work, which is to remove the smallest element and then get the LCM/GCD.\n\n- `650 / 752 testcases passed` if adopting removing the smallest number.\n- `746 / 752 testcases passed` if also comparing the result from LCM/GCD if there is not any removed element.\n- `All testcases passed` if we fully compare all possible candidates.\n\n# Complexity\n- Time complexity:\n`O(N^2)`\n\n# Code\n```java []\nclass Solution {\n public long maxScore(int[] nums) {\n if (nums.length == 1) {\n long n = (long) nums[0];\n return n*n;\n }\n\n Arrays.sort(nums);\n\n long lcm = (long) nums[0];\n long gcd = (long) nums[0];\n\n for (int i = 1; i < nums.length; i++) {\n long n = (long) nums[i];\n lcm = getLcm(n, lcm);\n gcd = n * gcd / getLcm(gcd, n);\n }\n\n long res = lcm * gcd;\n\n for (int i = 0; i < nums.length; i++) {\n res = Math.max(res, getProduct(nums, i));\n }\n\n return res;\n }\n\n private long getLcm(long a, long b) {\n if (a < b) {\n return getLcm(b, a);\n }\n\n while (a % b > 0) {\n long r = a % b;\n a = b;\n b = r;\n }\n\n return b;\n }\n\n private long getProduct(int[] nums, int skipIdx) {\n long lcm = skipIdx == 0 ? (long) nums[1] : (long) nums[0];\n long gcd = skipIdx == 0 ? (long) nums[1] : (long) nums[0];\n\n for (int i = 0; i < nums.length; i++) {\n if (i == skipIdx) continue;\n\n long n = (long) nums[i];\n lcm = getLcm(n, lcm);\n gcd = n * gcd / getLcm(gcd, n);\n }\n\n return lcm * gcd;\n }\n}\n``` | 0 | 0 | ['Greedy', 'Java'] | 0 |
find-the-maximum-factor-score-of-array | Easy Approach C++,100% accepted solution | easy-approach-c100-accepted-solution-by-ozu5h | Intuition\n### Brute force: \nUse two loops to find the solution. However, this would be inefficient for large arrays.\n\n### Optimized approach:\n\n- Use prefi | ss_ww_1 | NORMAL | 2024-10-27T20:51:42.695812+00:00 | 2024-10-27T20:51:42.695833+00:00 | 2 | false | # Intuition\n### Brute force: \nUse two loops to find the solution. However, this would be inefficient for large arrays.\n\n### Optimized approach:\n\n- Use prefix and suffix arrays.\n- First, calculate the gcd and lcm of all the elements ahead of the current index and store them in arrays using a loop.\n- Then, iterate through the array and keep storing the results to compute the maximum score.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialize Variables:\n\n - gcdbehind to 0, which will keep track of the gcd of elements before the current index.\n - lcmbehind to 1, which will keep track of the lcm of elements before the current index.\n - gcdahead to 0, which will be used to store the gcd of elements after the current index.\n - lcmahead to 1, which will be used to store the lcm of elements after the current index.\n - ans to 0, which will store the maximum score.\n2. Create Prefix Arrays:\n\n - gcdah to store the gcd of all elements after the current index.\n - lcmah to store the lcm of all elements after the current index.\n3. Compute Prefix Arrays:\n\n - Traverse the array from the end to the beginning to populate gcdah and lcmah.\n4. Iterate Through the Array:\n\n - For each index, compute two temporary scores using the prefix and suffix values.\n - Update gcdbehind and lcmbehind with the current element.\n - Update ans with the maximum of the current scores.\n5. Return the Result:\n - Return the value of ans.\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long maxScore(vector<int>& nums) {\n int n = nums.size();\n if (n == 0) {\n return 0;\n }\n long long gcdbehind = 0;\n long long lcmbehind = 1;\n long long gcdahead = 0;\n long long lcmahead = 1;\n long long ans = 0;\n vector<long long> gcdah(n, 1);\n vector<long long> lcmah(n, 1);\n\n for (int i = n - 1; i >= 0; --i) {\n gcdah[i] = gcdahead;\n lcmah[i] = lcmahead;\n gcdahead = gcd(gcdahead, nums[i]);\n lcmahead = lcm(lcmahead, nums[i]);\n }\n\n for (int i = 0; i < n; ++i) {\n long long temp1 =\n gcd(gcdbehind, gcdah[i]) * lcm(lcmbehind, lcmah[i]);\n lcmbehind = lcm(lcmbehind, nums[i]);\n gcdbehind = gcd(gcdbehind, nums[i]);\n long long temp2 =\n gcd(gcdbehind, gcdah[i]) * lcm(lcmbehind, lcmah[i]);\n ans = max({ans, temp1, temp2});\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | C++ solution of time complexity O(n^2) space complexity O(1) | c-solution-of-time-complexity-on2-space-ijp6d | Intuition\nTo solve the problem of finding the maximum score, which is defined as the product of the least common multiple (LCM) and the greatest common divisor | sumukhbendre | NORMAL | 2024-10-27T20:25:34.920071+00:00 | 2024-10-27T20:25:34.920096+00:00 | 13 | false | # Intuition\nTo solve the problem of finding the maximum score, which is defined as the product of the least common multiple (LCM) and the greatest common divisor (GCD) of a given array, we can think of two main operations:\n\n1. **GCD and LCM Calculations:** We need to compute the GCD and LCM of the entire array.\n2. **Deletion of Elements:** For each element in the array, if we consider removing it, we will recalculate the LCM and GCD for the remaining elements to see if we can get a higher score.\nOur goal is to maximize the score after possibly deleting one element from the array.\n\n# Approach\n1. GCD Function: Implement a recursive function to calculate the GCD using the Euclidean algorithm. This function will continue reducing the numbers until one becomes zero.\n\n2. LCM Function: Define an LCM function that utilizes the relationship between GCD and LCM:\n\n**LCM(\uD835\uDC4E,\uD835\uDC4F) = (\uD835\uDC4E\xD7\uD835\uDC4F)/GCD(\uD835\uDC4E,\uD835\uDC4F)**\n\n \n3. GCD of Array: Write a function to calculate the GCD of all elements in the array. Start with the first element and iteratively compute the GCD with each subsequent element.\n\n4. LCM of Array: Similarly, write a function to compute the LCM of all elements in the array using a loop.\n\n5. Max Score Calculation: Initialize the maximum score by calculating the score using the LCM and GCD of the entire array. Then iterate through each element:\n\n- Remove the element.\n- Compute the LCM and GCD of the remaining elements.\n- Update the maximum score if the new score is higher.\n- Restore the element to its original position.\n\n6. Return the Maximum Score: After considering each element\'s removal, return the maximum score found.\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\nO(1)\n\n# Code\n```cpp []\nclass Solution {\nlong long gcd(long long a, long long b) {\n return b == 0 ? a : gcd(b, a % b);\n}\n\n// Function to calculate GCD of an entire array\nlong long gcdOfArray(const std::vector<int>& arr) {\n long long result = arr[0];\n for (size_t i = 1; i < arr.size(); i++) {\n result = gcd(result, arr[i]);\n // If at any point GCD becomes 1, we can stop early\n if (result == 1) {\n return 1;\n }\n }\n return result;\n}\nlong long lcm(long long a, long long b) {\n return (a / std::gcd(a, b)) * b;\n}\n\n// Function to calculate LCM of an entire array\nlong long lcmOfArray(const std::vector<int>& arr) {\n long long result = arr[0];\n for (size_t i = 1; i < arr.size(); i++) {\n result = lcm(result, arr[i]);\n // If result becomes too large, you might want to add overflow handling here\n }\n return result;\n}\npublic:\n long long maxScore(vector<int>& nums) {\n int n = nums.size();\n long long ans = lcmOfArray(nums)*gcdOfArray(nums);\n for(int i=0;i<n;i++){\n long long deletedValue = nums[i];\n nums.erase(nums.begin() + i);\n ans = max(ans,lcmOfArray(nums)*gcdOfArray(nums));\n nums.insert(nums.begin() + i, deletedValue);\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | Beats 100% efficient solution | beats-100-efficient-solution-by-vinaiinf-ixdk | 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 | vinaiinfo18 | NORMAL | 2024-10-27T18:42:51.401619+00:00 | 2024-10-27T18:42:51.401651+00:00 | 8 | 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```cpp []\nclass Solution {\npublic:\n long long gcd(long long a,long long b){\n if(a==0)return b;\n return gcd(b%a,a);\n }\n long long lcm(unsigned long long a,unsigned long long b){\n return (a*b)/gcd(a,b);\n }\n long long maxScore(vector<int>& nums) {\n if(nums.size()==1)return (long long)nums[0]*(long long)nums[0];\n long long gcd_=nums[0],n= nums.size(),lcm_=nums[0];\n long long int gds[n],gdsr[n],lcms[n],lcmsr[n];\n gds[0]=nums[0];\n gdsr[n-1]= nums[n-1];\n lcms[0]=nums[0];\n lcmsr[n-1]=nums[n-1];\n for(int i=1;i<nums.size();i++){\n gcd_ = gcd(gcd_,nums[i]);\n lcm_ = lcm(lcm_,nums[i]);\n gds[i]=gcd_;\n lcms[i]=lcm_;\n }\n gcd_=nums[n-1];\n lcm_=nums[n-1];\n for(int i=n-2;i>=0;i--){\n gcd_ = gcd(gcd_,nums[i]);\n lcm_ = lcm(lcm_,nums[i]);\n gdsr[i]=gcd_;\n lcmsr[i]=lcm_;\n }\n long long ans = gcd_*lcm_;\n for(int i=1;i<n-1;i++){\n gcd_=gcd(gds[i-1],gdsr[i+1]);\n lcm_=lcm(lcms[i-1],lcmsr[i+1]);\n long long temp =gcd_*lcm_;\n ans = max(ans,temp);\n }\n ans = max(ans,gdsr[1]*lcmsr[1]);\n ans = max(ans,gds[n-2]*lcms[n-2]);\n \n \n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
find-the-maximum-factor-score-of-array | O(n) Solution | Prefix and Suffix Array | on-solution-prefix-and-suffix-array-by-s-ibxt | Intuition and Approach\n Describe your approach to solving the problem. \nThe problem ask us to remove atmost one element and calculate the maximum score.\n\n# | sauram228 | NORMAL | 2024-10-27T17:22:33.156743+00:00 | 2024-10-27T17:22:33.156784+00:00 | 19 | false | # Intuition and Approach\n<!-- Describe your approach to solving the problem. -->\nThe problem ask us to remove atmost one element and calculate the maximum score.\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n long long gcd(long long a, long long b){\n if(a==0 ) return b;\n if(b==0) return a;\n return gcd(b, a%b);\n }\n long long maxScore(vector<int>& nums) {\n int n=nums.size();\n vector<long long> gcdleft(n+2,0);\n vector<long long> gcdright(n+2,0);\n vector<long long> lcmleft(n+2,1);\n vector<long long> lcmright(n+2,1);\n for(int i=1;i<=n;i++){\n gcdleft[i]=gcd(gcdleft[i-1],nums[i-1]);\n lcmleft[i]= (lcmleft[i-1]*nums[i-1])/gcd(lcmleft[i-1],nums[i-1]);\n }\n for(int i=n;i>0;i--){\n gcdright[i]=gcd(gcdright[i+1],nums[i-1]);\n lcmright[i]= (lcmright[i+1]*nums[i-1])/gcd(lcmright[i+1],nums[i-1]);\n }\n long long ans= gcdleft[n]*lcmleft[n];\n long long ans1= gcdright[1]*lcmright[1];\n assert(ans==ans1);\n for(int i=1;i<=n;i++){\n long long tempgcd = gcd(lcmleft[i-1],lcmright[i+1]);\n ans=max(ans, ((lcmleft[i-1]/tempgcd)*(lcmright[i+1]) * gcd(gcdleft[i-1], gcdright[i+1])));\n }\n return ans;\n }\n};\n``` | 0 | 0 | ['C++'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.