Table of Contents

SolutionImplementation

Solution

The problem asks us to find the maximum possible GCD of the remaining N1N-1 numbers after taking any one of them away. Naively trying every single combination will result in a complexity of O(N2+Nlog(maxai))\mathcal{O}(N^2 + N \log(\max a_i)) as there are NN different ways to take away a number and calculating the GCD will take O(N+log(maxai))\mathcal{O}(N+\log(\max a_i)) time per case.

To speed this process up, we can calculate the GCDs of every prefix and suffix. Let l[i]=gcdj=1ia[j]l[i] = \gcd_{j=1}^{i} a[j] and r[i]=gcdj=iNa[j]r[i] = \gcd_{j=i}^{N} a[j]. Then the answer is the maximum of gcd(l[i1],r[i+1]),\gcd(l[i-1],r[i+1]), i[1,N]i \in [1,N].

Time Complexity: O(N+log(maxai))\mathcal{O}(N+\log(\max a_i))

Time Complexity Proof

Implementation

import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
Kattio io = new Kattio();
int n = io.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) { a[i] = io.nextInt(); }

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!