- 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
- 58 lines of C++ from the credited upstream file 3334.cpp.
- The implementation visibly relies on sequence storage.
- 3 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.
1class Solution {2 public:3 long long maxScore(vector<int>& nums) {4 const int n = nums.size();5 6 7 const auto [prefixGcd, prefixLcm] = getPrefix(nums);8 9 10 const auto [suffixGcd, suffixLcm] = getSuffix(nums);11 long ans = suffixGcd[0] * suffixLcm[0];12 13 for (int i = 0; i < n; ++i) {14 const long gcd1 = i > 0 ? prefixGcd[i - 1] : 0;15 const long gcd2 = i + 1 < n ? suffixGcd[i + 1] : 0;16 const long lcm1 = i > 0 ? prefixLcm[i - 1] : 1;17 const long lcm2 = i + 1 < n ? suffixLcm[i + 1] : 1;18 const long score = gcd(gcd1, gcd2) * lcm(lcm1, lcm2);19 ans = max(ans, score);20 }21 22 return ans;23 }24 25 private:26 27 pair<vector<long>, vector<long>> getPrefix(const vector<int>& nums) {28 vector<long> prefixGcd;29 vector<long> prefixLcm;30 long currGcd = 0;31 long currLcm = 1;32 for (const int num : nums) {33 currGcd = gcd(currGcd, num);34 currLcm = lcm(currLcm, num);35 prefixGcd.push_back(currGcd);36 prefixLcm.push_back(currLcm);37 }38 return {prefixGcd, prefixLcm};39 }40 41 42 pair<vector<long>, vector<long>> getSuffix(const vector<int>& nums) {43 vector<long> suffixGcd;44 vector<long> suffixLcm;45 long currGcd = 0;46 long currLcm = 1;47 for (int i = nums.size() - 1; i >= 0; --i) {48 currGcd = gcd(currGcd, nums[i]);49 currLcm = lcm(currLcm, nums[i]);50 suffixGcd.push_back(currGcd);51 suffixLcm.push_back(currLcm);52 }53 ranges::reverse(suffixGcd);54 ranges::reverse(suffixLcm);55 return {suffixGcd, suffixLcm};56 }57};58