- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 47 lines of Python from the credited upstream file 3334.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution:2 def maxScore(self, nums: list[int]) -> int:3 n = len(nums)4 5 6 prefixGcd, prefixLcm = self._getPrefix(nums)7 8 9 suffixGcd, suffixLcm = self._getSuffix(nums)10 ans = suffixGcd[0] * suffixLcm[0]11 12 for i in range(n):13 gcd1 = prefixGcd[i - 1] if i > 0 else 014 gcd2 = suffixGcd[i + 1] if i + 1 < n else 015 lcm1 = prefixLcm[i - 1] if i > 0 else 116 lcm2 = suffixLcm[i + 1] if i + 1 < n else 117 score = math.gcd(gcd1, gcd2) * math.lcm(lcm1, lcm2)18 ans = max(ans, score)19 20 return ans21 22 def _getPrefix(self, nums: list[int]) -> tuple[list[int], list[int]]:23 """Returns the prefix GCD and LCM arrays."""24 prefixGcd = []25 prefixLcm = []26 currGcd = 027 currLcm = 128 for num in nums:29 currGcd = math.gcd(currGcd, num)30 currLcm = math.lcm(currLcm, num)31 prefixGcd.append(currGcd)32 prefixLcm.append(currLcm)33 return prefixGcd, prefixLcm34 35 def _getSuffix(self, nums: list[int]) -> tuple[list[int], list[int]]:36 """Returns the suffix GCD and LCM arrays."""37 suffixGcd = []38 suffixLcm = []39 currGcd = 040 currLcm = 141 for num in reversed(nums):42 currGcd = math.gcd(currGcd, num)43 currLcm = math.lcm(currLcm, num)44 suffixGcd.append(currGcd)45 suffixLcm.append(currLcm)46 return list(reversed(suffixGcd)), list(reversed(suffixLcm))47