- Identify the ordered answer range or sorted search domain.
- Write a predicate whose truth changes only once.
- 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.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 long long maxGCDScore(vector<int>& nums, int k) {8 static const int INF = numeric_limits<int>::max();9 10 vector<int> lookup(size(nums));11 for (int i = 0; i < size(nums); ++i) {12 while ((nums[i] & 1) == 0) {13 nums[i] >>= 1;14 ++lookup[i];15 }16 }17 const int max_e = ranges::max(lookup);18 vector<vector<int>> lookup2(max_e + 1);19 for (int i = 0; i < size(lookup); ++i) {20 lookup2[lookup[i]].emplace_back(i);21 }22 int64_t result = 0;23 unordered_map<int, unordered_map<int, vector<int>>> dp;24 for (int i = 0; i < size(nums); ++i) {25 unordered_map<int, unordered_map<int, vector<int>>> new_dp;26 new_dp[nums[i]][lookup[i]] = {i, i};27 for (const auto& [g, e_v] : dp) { 28 for (const auto& [e, v] : e_v) {29 const int ng = gcd(g, nums[i]);30 const int ne = min(e, lookup[i]);31 if (!new_dp.count(ng) || !new_dp[ng].count(ne)) {32 new_dp[ng][ne] = {INF, INF};33 }34 new_dp[ng][ne][0] = min(new_dp[ng][ne][0], v[0]);35 const int left = distance(cbegin(lookup2[ne]), lower_bound(cbegin(lookup2[ne]), cend(lookup2[ne]), v[0])); 36 const int right = distance(cbegin(lookup2[ne]), upper_bound(cbegin(lookup2[ne]), cend(lookup2[ne]), i)) - 1; 37 new_dp[ng][ne][1] = min(new_dp[ng][ne][1], (right - left + 1 <= k) ? v[0] : lookup2[ne][right - k] + 1);38 }39 }40 dp = move(new_dp);41 for (const auto& [g, e_v] : dp) { 42 for (const auto& [e, v] : e_v) {43 result = max(result, (static_cast<int64_t>(g) * (i - v[0] + 1)) << e);44 result = max(result, (static_cast<int64_t>(g) * (i - v[1] + 1)) << (e + 1));45 }46 }47 }48 return result;49 }50};51 52535455class Solution2 {56public:57 long long maxGCDScore(vector<int>& nums, int k) {58 static const int INF = numeric_limits<int>::max();59 60 const auto& lower_bit = [](int x) {61 return x & -x;62 };63 64 int64_t result = 0;65 for (int i = 0; i < size(nums); ++i) {66 for (int j = i, g = 0, mn = INF, cnt = 0; j < size(nums); ++j) {67 g = gcd(g, nums[j]);68 const auto& bit = lower_bit(nums[j]);69 if (bit < mn) {70 mn = bit;71 cnt = 0;72 }73 if (bit == mn) {74 ++cnt;75 }76 result = max(result, static_cast<int64_t>(g) * (j - i + 1) * (cnt <= k ? 2 : 1));77 if (static_cast<int64_t>(g) * (size(nums) - i) * 2 <= result) {78 break;79 }80 }81 }82 return result;83 }84};85