Problem solution · C++

Maximize Subarray Gcd Score

Maximize Subarray Gcd Score: a C++ solution using binary search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Binary search
Source
Kamyu LeetCode Solutions
Length
85 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Binary search

For Maximize Subarray Gcd Score, the implementation exploits a monotonic condition to discard half of the remaining search space after every check.

  1. Identify the ordered answer range or sorted search domain.
  2. Write a predicate whose truth changes only once.
  3. Move the appropriate boundary after each midpoint check and return the final feasible position.

Code notes

  • 85 lines of C++ from the credited upstream file maximize-subarray-gcd-score.cpp.
  • The implementation visibly relies on sequence storage, hash lookup.
  • 10 loop blocks detected.

Complexity

Multiply the logarithmic number of midpoint checks by the cost of one predicate evaluation.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codeMaximize Subarray Gcd Score · C++C++
Use this to learn the idea, then write your own version.
// Time:  O(nlogn * logr), r = max(nums)// Space: O(n + logr) // number theory, suffix-gcd states, dp, binary searchclass Solution {public:    long long maxGCDScore(vector<int>& nums, int k) {        static const int INF = numeric_limits<int>::max();         vector<int> lookup(size(nums));        for (int i = 0; i < size(nums); ++i) {            while ((nums[i] & 1) == 0) {                nums[i] >>= 1;                ++lookup[i];            }        }        const int max_e = ranges::max(lookup);        vector<vector<int>> lookup2(max_e + 1);        for (int i = 0; i < size(lookup); ++i) {            lookup2[lookup[i]].emplace_back(i);        }        int64_t result = 0;        unordered_map<int, unordered_map<int, vector<int>>> dp;        for (int i = 0; i < size(nums); ++i) {            unordered_map<int, unordered_map<int, vector<int>>> new_dp;            new_dp[nums[i]][lookup[i]] = {i, i};            for (const auto& [g, e_v] : dp) {  // |g * e| = O(logr)                for (const auto& [e, v] : e_v) {                    const int ng = gcd(g, nums[i]);                    const int ne = min(e, lookup[i]);                    if (!new_dp.count(ng) || !new_dp[ng].count(ne)) {                        new_dp[ng][ne] = {INF, INF};                    }                    new_dp[ng][ne][0] = min(new_dp[ng][ne][0], v[0]);                    const int left = distance(cbegin(lookup2[ne]), lower_bound(cbegin(lookup2[ne]), cend(lookup2[ne]), v[0]));  // Time: O(logn)                    const int right = distance(cbegin(lookup2[ne]), upper_bound(cbegin(lookup2[ne]), cend(lookup2[ne]), i)) - 1;  // Time: O(logn)                    new_dp[ng][ne][1] = min(new_dp[ng][ne][1], (right - left + 1 <= k) ? v[0] : lookup2[ne][right - k] + 1);                }            }            dp = move(new_dp);            for (const auto& [g, e_v] : dp) {  // |g * e| = O(logr)                for (const auto& [e, v] : e_v) {                    result = max(result, (static_cast<int64_t>(g) * (i - v[0] + 1)) << e);                    result = max(result, (static_cast<int64_t>(g) * (i - v[1] + 1)) << (e + 1));                }            }        }        return result;    }}; // Time:  O(n^2 + n * logr), r = max(nums)// Space: O(1)// number theory, brute forceclass Solution2 {public:    long long maxGCDScore(vector<int>& nums, int k) {        static const int INF = numeric_limits<int>::max();         const auto& lower_bit = [](int x) {            return x & -x;        };         int64_t result = 0;        for (int i = 0; i < size(nums); ++i) {            for (int j = i, g = 0, mn = INF, cnt = 0; j < size(nums); ++j) {                g = gcd(g, nums[j]);                const auto& bit = lower_bit(nums[j]);                if (bit < mn) {                    mn = bit;                    cnt = 0;                }                if (bit == mn) {                    ++cnt;                }                result = max(result, static_cast<int64_t>(g) * (j - i + 1) * (cnt <= k ? 2 : 1));                if (static_cast<int64_t>(g) * (size(nums) - i) * 2 <= result) {                    break;                }            }        }        return result;    }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗