J: A Simple Problem

3 篇文章 0 订阅
1 篇文章 0 订阅

Description
在一个由N个整数组成的数列中,最多能找到多少个位置连续的整数且其中的最大值与最小值之差不超过K呢?
Input
输入包含若干组数据。每组数据的第一行有2个正整数,N(1<=N<=10^6),K(0<=K<=10^6),其中N、K的含义同上,接下来一行一共有N个32位有符号整数(32-bit signed integer),依次描绘了这个数列中各个整数的值。
Output
对于每组数据,输出一个正整数,表示在这个数列中最多能找到多少个位置连续的整数且其中的最大值与最小值之差不超过K。
Sample Input
4 2
3 1 5 2

3 2
3 1 2
Sample Output
2
3


首先,排除暴力。然后想到了在扫描的时候发现不max-min>k时,
取下标为min(maxindex,minindex)+1。但是这样在下标之后的值还是会重新扫描,最坏情况就是递增序列。几乎跟暴力一样。
最后的解为:2个指针,当序列满足要求的时候right右移。反之,left右移。
其之间的序列放在一个multiset中维护。right右移,插入元素。left右移删除元素。注意left右移后要用迭代器删除,否则会删除所有与之相等的值(是最大最小值就会造成影响)。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <algorithm>
#include <string>
#include <set>
#include <map>
#define MIN(a,b) ((a)<(b)?(a):(b))
#define MAX(a,b) ((a)>(b)?(a):(b))
using namespace std;

char s[10], c[10];
long long int A[1000005];
int main()
{
    long long int x, y;
    long long int max = 0, min = 999999;
    multiset<long long int>ss;

    while (scanf_s("%lld%lld", &x, &y) != EOF) {
        for (long long int i = 0; i < x; i++) {
            scanf_s("%lld", &A[i]);
        }
        long long int nlen = 0;
        long long int maxi = 0, mini = 0;
        long long int left = 0, right = 0;
        ss.insert(A[0]);
        while (right!=x) {
            max = *(--ss.end());
            min = *ss.begin();
            if (max - min <= y) {
                nlen = right - left + 1 > nlen ? right - left + 1 : nlen;
                ss.insert(A[++right]);
            }
            else {
                auto pos = ss.find(A[left++]);
                ss.erase(pos);
            }
        }
        cout << nlen << endl;
        ss.clear();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值