Description
给定一个序列 (a_i),要找两个数 (i,j),使得 (a_i ge a_j) 并且 (a_i mod a_j) 的值最大,求 (a_i mod a_j) 的最大值。
Solution
考虑 (a mod b = a-kb),其中 (kb le a < (k+1)b)
考虑枚举 (k,b),可以通过二分找到最大的 (a),显然此时余数也最大
复杂度 (O(n log^2 n))
#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1000005;
int n,a[N],c[N],ans;
signed main()
{
ios::sync_with_stdio(false);
cin>>n;
for(int i=1;i<=n;i++) cin>>a[i],c[a[i]]++;
sort(a+1,a+n+1);
for(int b=1;b<=1e6;b++)
{
if(c[b]==0) continue;
for(int k=0;k*b<=1e6;k++)
{
int x=*(lower_bound(a+1,a+n+1,(k+1)*b)-1);
if(x>=b) ans=max(ans,x%b);
}
}
cout<<ans<<endl;
}