- 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
- 84 lines of C++ from the credited upstream file good-subsequence-queries.cpp.
- The implementation visibly relies on sequence storage.
- 7 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.
1234 56const auto& precompute = [](int r) {7 vector<vector<int>> factors(r + 1);8 int curr = 1, k = 0;9 for (int i = 2; i < size(factors); i++) {10 if (!empty(factors[i])) {11 continue;12 }13 if (curr * i <= r) {14 curr *= i;15 ++k;16 }17 for (int j = i; j < size(factors); j += i) {18 factors[j].emplace_back(i);19 }20 }21 return pair(factors, k);22};23 24const int MAX_NUMS = 50000;25const auto& [FACTORS, K] = precompute(MAX_NUMS);26class Solution {27public:28 int countGoodSubseq(vector<int>& nums, int p, vector<vector<int>>& queries) {29 if (size(nums) == 1) {30 return 0;31 }32 int curr = 0;33 int mx = ranges::max(nums);34 for (const auto& q : queries) {35 mx = max(mx, q[1]);36 }37 vector<int> cnt(mx + 1), cnt2(size(nums) + 1);38 const auto& update = [&](int x, int d) {39 if (x % p) {40 return;41 }42 for (const auto& q : FACTORS[x / p]) {43 --cnt2[cnt[q]];44 cnt[q] += d;45 ++cnt2[cnt[q]];46 }47 curr += d;48 };49 50 const auto& check = [&]() {51 if (curr == 0 || cnt2[curr]) {52 return false;53 }54 if (curr != size(nums) || size(nums) > K) {55 return true;56 }57 for (int i = 0; i < size(nums); ++i) {58 update(nums[i], -1);59 const auto& found = (cnt2[curr] == 0);60 update(nums[i], +1);61 if (found) {62 return true;63 }64 }65 return false;66 };67 68 int result = 0;69 for (const auto& x : nums) {70 update(x, +1);71 }72 for (const auto& q : queries) {73 const auto& i = q[0], &x = q[1];74 update(nums[i], -1);75 nums[i] = x;76 update(nums[i], +1);77 if (check()) {78 ++result;79 }80 }81 return result;82 }83};84