- 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
- 63 lines of C++ from the credited upstream file divisible-game.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 8 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 56vector<int> linear_sieve_of_eratosthenes(int n) { 7 vector<int> spf(n + 1, -1);8 vector<int> primes;9 for (int i = 2; i <= n; ++i) {10 if (spf[i] == -1) {11 spf[i] = i;12 primes.emplace_back(i);13 }14 for (const auto& p : primes) {15 if (i * p > n || p > spf[i]) {16 break;17 }18 spf[i * p] = p;19 }20 }21 return spf;22}23 24const int MAX_NUMS = 1e6;25const auto& SPF = linear_sieve_of_eratosthenes(MAX_NUMS);26class Solution {27public:28 int divisibleGame(vector<int>& nums) {29 static const int MOD = 1e9 + 7;30 31 vector<int> prefix(size(nums) + 1);32 for (int i = 0; i < size(nums); ++i) {33 prefix[i + 1] = prefix[i] + nums[i];34 }35 unordered_map<int, vector<int>> lookup;36 for (int i = 0; i < size(nums); ++i) {37 int x = nums[i];38 while (x != 1) {39 const auto& p = SPF[x];40 lookup[p].emplace_back(i);41 while (x % p == 0) {42 x /= p;43 }44 }45 }46 int best_diff = -ranges::min(nums), best_k = 2;47 for (const auto& [p, idxs] : lookup) {48 int total = 0, j = -1;49 for (const auto& i : idxs) {50 total = max(total - (prefix[(i - 1) + 1] - prefix[j + 1]), 0) + nums[i];51 if (total > best_diff) {52 best_diff = total;53 best_k = p;54 } else if (total == best_diff) {55 best_k = min(best_k, p);56 }57 j = i;58 }59 }60 return ((static_cast<int64_t>(best_diff) * best_k) % MOD + MOD) % MOD;61 }62};63