abc182_b - Almost Gcd

Count number of elements divisible by $k$ for each $2 \geq k \geq a_{max}$.

Time complexity: $O(a_{max} \times n)$

Memory complexity: $O(n)$

Click to show code.


using namespace std;
using ll = long long;
using ii = pair<int, int>;
using vi = vector<int>;
int solve(vi a)
{
    int amax = *max_element(begin(a), end(a));
    ii ans = {0, 0};
    for (int k = 2; k <= amax; ++k)
    {
        int cur = count_if(begin(a), end(a), [k](int ai) { return ai % k == 0; });
        ans = max(ans, {cur, k});
    }
    return ans.second;
}
int main(void)
{
    ios::sync_with_stdio(false), cin.tie(NULL);
    int n;
    cin >> n;
    vi a(n);
    for (auto &ai : a)
        cin >> ai;
    cout << solve(a) << endl;
    return 0;
}