You are viewing a single comment's thread. Return to all comments →
C++ solution
#include <bits/stdc++.h> using namespace std; int n; vector<long long int> v; vector<pair<long long int, pair<long long int, long long int>>> vl; vector<pair<long long int, pair<long long int, long long int>>> vr; map<long long int, long long int> mp; long long int ans; long long int gcd(long long int a, long long int b){ if(a > b){ swap(a, b); } while(a){ swap(a, b); a %= b; } return b; } long long int lcm(long long int a, long long int b){ return a / gcd(a, b) * b; } inline void solve(int l, int r){ int mid = (l + r) >> 1; { vl.clear(); long long int sum = 0; long long int mx = v[mid]; int gc = 0; for(int j = mid; j <= r; j++){ sum += v[j]; gc = gcd(gc, abs(v[j]) ); mx = max(mx, v[j]); ans = max(ans, gc*(sum - mx)); vl.push_back(make_pair(mx, make_pair(sum, gc))); } } { vr.clear(); long long int sum = 0; long long int mx = v[mid]; int gc = 0; for(int j = mid; j >=l; j--){ sum += v[j]; gc = gcd(gc, abs(v[j]) ); mx = max(mx, v[j]); ans = max(ans, gc*(sum - mx)); vr.push_back(make_pair(mx, make_pair(sum, gc))); } } sort(vl.begin(), vl.end()); sort(vr.begin(), vr.end()); int idx = 0; mp.clear(); for(int i = 0; i < vl.size(); i++){ while(idx < vr.size() && vr[idx].first <= vl[i].first){ int gc = vr[idx].second.second; if(mp.count(gc) == 0){ mp[gc] = LLONG_MIN; } mp[gc] = max(mp[gc], vr[idx].second.first-v[mid]); idx++; } for(auto it = mp.begin(); it != mp.end(); it++){ long long int G = gcd((*it).first, vl[i].second.second); long long int SUM = (*it).second + vl[i].second.first; long long int MX = vl[i].first; G *= (SUM - MX); ans = max(ans, G); } } mp.clear(); swap(vl, vr); idx = 0; for(int i = 0; i < vl.size(); i++){ while(idx < vr.size() && vr[idx].first <= vl[i].first){ int gc = vr[idx].second.second; if(mp.count(gc) == 0){ mp[gc] = LLONG_MIN; } mp[gc] = max(mp[gc], vr[idx].second.first - v[mid]); idx++; } for(auto it = mp.begin(); it != mp.end(); it++){ long long int G = gcd((*it).first, vl[i].second.second); long long int SUM = (*it).second + vl[i].second.first; long long int MX = vl[i].first; G *= (SUM - MX); ans = max(ans, G); } } if(l <= mid - 1) solve(l, mid - 1); if(mid + 1 <= r) solve(mid + 1, r); } int main(){ cin >> n; for(int i = 0; i < n; i++){ int a; scanf("%d", &a); v.push_back(a); } solve(0, n - 1); printf("%lld\n", ans); return 0; }
Seems like cookies are disabled on this browser, please enable them to open this website
The Strange Function
You are viewing a single comment's thread. Return to all comments →
C++ solution