Solution
The problem asks us to find the maximum possible GCD of the remaining numbers after taking any one of them away. Naively trying every single combination will result in a complexity of as there are different ways to take away a number and calculating the GCD will take time per case.
To speed this process up, we can calculate the GCDs of every prefix and suffix. Let and . Then the answer is the maximum of .
Time Complexity:
Time Complexity Proof
Implementation
C++
#include <bits/stdc++.h>using namespace std;const int maxN = 1e5 + 5;int arr[maxN];int prefGcd[maxN]; // prefGcd[i] = GCD of a1,a2, ..., aiint suffGcd[maxN]; // suffGcd[i] = GCD of ai, ai+1, ..., anint N;
Python
from math import gcdn = int(input())arr = list(map(int, input().split()))ans = 0prefix_gcd = [0] * nprefix_gcd[0] = arr[0]
Java
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!