- Decide the key that represents the information needed later.
- Update its count or stored state while scanning the input.
- Use constant-time expected lookups to detect matches or assemble the result.
Code notes
- 53 lines of Python from the credited upstream file divisible-game.py.
- The implementation visibly relies on sequence storage, hash lookup.
- No explicit loop blocks detected.
Complexity
Expected hash operations are constant time, but the surrounding scan and the number of stored keys determine total work and memory.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1234 5import collections6 7 89def linear_sieve_of_eratosthenes(n): 10 primes = []11 spf = [-1]*(n+1) 12 for i in xrange(2, n+1):13 if spf[i] == -1:14 spf[i] = i15 primes.append(i)16 for p in primes:17 if i*p > n or p > spf[i]:18 break19 spf[i*p] = p20 return spf21 22 23MAX_NUMS = 10**624SPF = linear_sieve_of_eratosthenes(MAX_NUMS)25class Solution(object):26 def divisibleGame(self, nums):27 """28 :type nums: List[int]29 :rtype: int30 """31 MOD = 10**9+732 prefix = [0]*(len(nums)+1)33 for i in xrange(len(nums)):34 prefix[i+1] = prefix[i]+nums[i]35 lookup = collections.defaultdict(list)36 for i, x in enumerate(nums):37 while x != 1:38 p = SPF[x]39 lookup[p].append(i)40 while x%p == 0:41 x = p42 best_diff, best_k = -min(nums), 243 for p, idxs in lookup.iteritems():44 total, j = 0, -145 for i in idxs:46 total = max(total-(prefix[(i-1)+1]-prefix[j+1]), 0)+nums[i]47 if total > best_diff:48 best_diff, best_k = total, p49 elif total == best_diff:50 best_k = min(best_k, p)51 j = i52 return (best_diff*best_k)%MOD53