Maximum Value

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;
}
 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值