- Choose the invariant that makes a window valid or useful.
- Advance the right boundary and add the new element.
- Move the left boundary only as needed while maintaining the invariant and updating the answer.
Code notes
- 68 lines of Python from the credited upstream file 2818.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit loop blocks detected.
Complexity
Confirm that neither pointer moves backwards; if so, the scan is usually linear apart from the window’s data-structure operations.
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 maximumScore(self, nums: list[int], k: int) -> int:3 MOD = 1_000_000_0074 n = len(nums)5 ans = 16 minPrimeFactors = self._sieveEratosthenes(max(nums) + 1)7 primeScores = [self._getPrimeScore(num, minPrimeFactors) for num in nums]8 9 10 left = [-1] * n11 12 13 right = [n] * n14 stack = []15 16 17 for i in reversed(range(n)):18 while stack and primeScores[stack[-1]] <= primeScores[i]:19 left[stack.pop()] = i20 stack.append(i)21 22 stack = []23 24 25 for i in range(n):26 while stack and primeScores[stack[-1]] < primeScores[i]:27 right[stack.pop()] = i28 stack.append(i)29 30 numAndIndexes = [(num, i) for i, num in enumerate(nums)]31 32 def modPow(x: int, n: int) -> int:33 if n == 0:34 return 135 if n % 2 == 1:36 return x * modPow(x, n - 1) % MOD37 return modPow(x * x % MOD, n 2)38 39 for num, i in sorted(numAndIndexes, key=lambda x: (-x[0], x[1])):40 41 42 43 rangeCount = (i - left[i]) * (right[i] - i)44 actualCount = min(rangeCount, k)45 k -= actualCount46 ans *= modPow(num, actualCount)47 ans %= MOD48 49 return ans50 51 def _sieveEratosthenes(self, n: int) -> list[int]:52 """Gets the minimum prime factor of i, where 2 <= i <= n."""53 minPrimeFactors = [i for i in range(n + 1)]54 for i in range(2, int(n**0.5) + 1):55 if minPrimeFactors[i] == i: 56 for j in range(i * i, n, i):57 minPrimeFactors[j] = min(minPrimeFactors[j], i)58 return minPrimeFactors59 60 def _getPrimeScore(self, num: int, minPrimeFactors: list[int]) -> int:61 primeFactors = set()62 while num > 1:63 divisor = minPrimeFactors[num]64 primeFactors.add(divisor)65 while num % divisor == 0:66 num = divisor67 return len(primeFactors)68