Maximum Value(枚举剪枝+二分)
You are given a sequence a consisting of n integers. Find the maximum possible value of (integer remainder of ai divided by aj), where 1 ≤ i, j ≤ n and ai ≥ aj.
Input
The first line contains integer n — the length of the sequence (1 ≤ n ≤ 2·10^5).
The second line contains n space-separated integers ai (1 ≤ ai ≤ 10^6).
Output
Print the answer to the problem.
Examples
Input
3
3 4 5
Output
2
思路:
从数据范围上看不能直接暴力枚举,然后就想到剪枝+二分,首先aj可以对数组排序之后从后往前找,这样找到ans如果已经大于下一个aj-1就不用继续找了,同时对于每一个aj我们用二分找到它每个倍数对应的ai,注意这样找到的ai还要再往前找才是我们想要的最大的mod数,最后 一定要注意代码循环的范围!!! 想清楚再写。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=200005;
int a[N];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
int n;
cin>>n;
for(int i=0;i<n;i++)cin>>a[i];
sort(a,a+n);
int ans=0;
for(int i=n-1;i>=0;i--)//从后往前遍历方便后续剪枝
{
if(ans>a[i]-1) break;
if(i<n-1&&a[i]==a[i+1])continue;//去重
for(int j=2*a[i];j<=a[n-1];j+=a[i])//注意从2*a[i]开始
{
int k=lower_bound(a,a+n,j)-a;
if(k==0)continue;
k--;
if(a[k]<=j-a[i])continue;//该区间无更新
ans=max(ans,a[k]%a[i]);
}
ans=max(ans,a[n-1]%a[i]);//如果a[n-1]<2*a[i],也要更新ans
}
cout<<ans<<endl;
return 0;
}