abc169_b - Multiplication 2

Test for $a_i \leq \frac{10^{18}}{\text{ans}}$.

Time complexity: $O(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>;
ll solve(vector<ll> a)
{
    if (auto it = find(begin(a), end(a), 0LL); it != a.end())
        return 0LL;
    ll ans = 1, maxv = 1e18;
    for (auto ai : a)
    {
        if (ai <= maxv / ans)
            ans *= ai;
        else
            return -1;
    }
    return ans;
}
int main(void)
{
    ios::sync_with_stdio(false), cin.tie(NULL);
    int n;
    cin >> n;
    vector<ll> a(n);
    for (auto &ai : a)
        cin >> ai;
    cout << solve(a) << endl;
    return 0;
}