给定一个数组a,找a[i]%a[j] (a[i]>=a[j],1<=i,j<=n)的最大值
观察到ai<=1e6因此,做桶解题,手算样例可以观察到ai的最大余数出现一定是模大于它的1/2时,反过来想,则是当向右靠近模的倍数的数更能计算出更大的余数,因此预处理出原本数据中的数的prei,最向右靠近i的数,再枚举倍数,取最大值即是ans
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#include<map>
#include<set>
#include<vector>
#include<algorithm>
#include<string>
#include<bitset>
#include<cmath>
#include<array>
#include<atomic>
#include<sstream>
#include<stack>
#include<iomanip>
//#include<bits/stdc++.h>
//#define int ll
#define pb push_back
#define endl '\n'
#define x first
#define y second
#define Endl endl
#define pre(i,a,b) for(int i=a;i<=b;i++)
#define rep(i,b,a) for(int i=b;i>=a;i--)
#define si(x) scanf("%d", &x);
#define sl(x) scanf("%lld", &x);
#define ss(x) scanf("%s", x);
#define YES {puts("YES");return;}
#define NO {puts("NO"); return;}
#define all(x) x.begin(),x.end()
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef pair<int, PII> PIII;
typedef pair<char, int> PCI;
typedef pair<int, char> PIC;
typedef pair<double, double> PDD;
typedef pair<ll, ll> PLL;
const int N = 200010, M = 2 * N, B = N, MOD = 998244353;
const int INF = 0x3f3f3f3f;
const ll LLINF = 0x3f3f3f3f3f3f3f3f;
int dx[4] = { -1,0,1,0 }, dy[4] = { 0,1,0,-1 };
int n, m, k;
bool has[2000010];
int pre[2000010];
ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
ll lowbit(ll x) { return x & -x; }
ll qmi(ll a, ll b, ll mod) {
ll res = 1;
while (b) {
if (b & 1) res = res * a % mod;
a = a * a % mod;
b >>= 1;
}
return res;
}
inline void init() { }
void slove()
{
cin >> n;
int mx = 0;
pre(i, 1, n) {
int x;
si(x);
has[x] = true;
pre[x] = -1;
mx = max(mx, x);
}
int p = 0, q = 0;
while (p <= mx * 2)
{
while (p <= mx * 2 && pre[p] != -1)p++;
pre(i, q + 1, p) pre[i] = q;
q = p;
}
int ans = 0;
pre(i, 1, mx)
if (has[i])
{
for(int j = i * 2; j <= mx * 2;j += i)
ans = max(ans, pre[j] % i);
}
cout << ans << endl;
}
signed main()
{
int _;
//si(_);
_ = 1;
init();
while (_--)
{
slove();
}
return 0;
}