a[i]=k*a[j]+m
m即是所求
从大到小枚举a[j]后,枚举倍数k
用到了stl里的low_bound()
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include"cstdio" #include"cstring" #include"algorithm" #define MAXN 1000005 using namespace std; int num[MAXN],n; int get_ans(int x) { int temp=x,ans=0; while(temp<num[n-1]){ temp+=x; int pos=lower_bound(num,num+n,temp)-num; if(!pos) continue; else pos--; ans=max(ans,num[pos]%x); } return ans; } int main() { while(scanf("%d",&n)!=EOF){ for(int i=0;i<n;i++) scanf("%d",&num[i]); sort(num,num+n); int ans=0; for(int i=n-1;i>=0;i--){ if(ans>=num[i]) break; if(num[i]==num[i+1]&&i!=n-1) continue; ans=max(ans,get_ans(num[i])); } printf("%d\n",ans); } return 0; }