文章目录
Maximum Value
You are given a sequence a consisting of n integers. Find the maximum possible value of (integer remainder of a i _i i divided by a j _j j), where 1 ≤ i, j ≤ n and a i _i i ≥ a j _j j.
Input
The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·10
5
^5
5).
The second line contains n space-separated integers a i (1 ≤ a i _i i ≤ 10 6 ^6 6).
Output
Print the answer to the problem.
Examples
inputCopy
3
3 4 5
outputCopy
2
二分出对于小于每个倍数的最大值
#include <bits/stdc++.h>
using namespace std;
const int maxn=2e5+7;
int a[maxn];
int main()
{
int n;
scanf("%d",&n);
for(int i=1; i<=n; i++) scanf("%d",&a[i]);
sort(a+1,a+1+n);
int ans=0;
for(int i=1; i<=n; i++)
{
if(i==1||a[i]!=a[i-1])
{
for(int j=2;j*a[i]<=a[n];j++)
{
int t=lower_bound(a+1,a+1+n,j*a[i])-a;
ans=max(ans,a[t-1]%a[i]);
}
ans=max(ans,a[n]%a[i]);
}
}
printf("%d\n",ans);
return 0;
}