- 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
- 56 lines of Python from the credited upstream file maximum-score-with-co-prime-element.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.
123 45class Solution(object):6 def maxScore(self, nums, maxVal):7 """8 :type nums: List[int]9 :type maxVal: int10 :rtype: int11 """12 def linear_sieve_of_eratosthenes(n): 13 primes = []14 spf = [-1]*(n+1) 15 for i in xrange(2, n+1):16 if spf[i] == -1:17 spf[i] = i18 primes.append(i)19 for p in primes:20 if i*p > n or p > spf[i]:21 break22 spf[i*p] = p23 return spf24 25 26 def mobius(spf): 27 mu = [0]*len(spf)28 for i in xrange(1, len(mu)):29 mu[i] = 1 if i == 1 else 0 if spf[ispf[i]] == spf[i] else -mu[ispf[i]]30 return mu31 32 mx = max(max(nums), maxVal)33 spf = linear_sieve_of_eratosthenes(mx)34 mu = mobius(spf)35 cnt = [0]*(mx+1)36 for x in nums:37 cnt[x] += 138 multiple_cnt = [0]*(mx+1)39 for i in xrange(1, mx+1):40 for j in xrange(i, mx+1, i):41 multiple_cnt[i] += cnt[j]42 coprime_cnt = [0]*(mx+1)43 for i in xrange(1, mx+1):44 if not mu[i]*multiple_cnt[i]:45 continue46 for j in xrange(i, mx+1, i):47 coprime_cnt[j] += mu[i]*multiple_cnt[i]48 result = 049 for i in xrange(1, mx+1):50 c = len(nums)-coprime_cnt[i]51 if cnt[i]:52 result = max(result, i-(c-1 if i != 1 else 0))53 elif i <= maxVal:54 result = max(result, i-max(c, 1))55 return result56