G - Good subsequence

本文介绍了一个算法问题,即在给定序列中找到最大长度的好子序列,其中好子序列定义为连续子序列且其最大值与最小值之差不大于给定阈值k。文章通过示例解释了问题,并提供了一段C++代码实现解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

G - Good subsequence
Time Limit:2000MS     Memory Limit:262144KB     64bit IO Format:%lld & %llu

Description

Give you a sequence of n numbers, and a number k you should find the max length of Good subsequence. Good subsequence is a continuous subsequence of the given sequence and its maximum value - minimum value<=k. For example n=5, k=2, the sequence ={5, 4, 2, 3, 1}. The answer is 3, the good subsequence are {4, 2, 3} or {2, 3, 1}.

Input

There are several test cases.
Each test case contains two line. the first line are two numbers indicates n and k (1<=n<=10,000, 1<=k<=1,000,000,000). The second line give the sequence of n numbers a[i] (1<=i<=n, 1<=a[i]<=1,000,000,000). 
The input will finish with the end of file.

Output

For each the case, output one integer indicates the answer.

Sample Input

5 2
5 4 2 3 1
1 1
1

Sample Output

3
1



//HDU1171:Big Event in HDU

#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
using namespace std;


int a[10005]; 
 
int main() 
{
int n,k,i,j;
while(scanf("%d%d",&n,&k)!=EOF)
{
for (i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}


/// sort(a+1,a+1+n);        不能手残排序
int max;
int min;
int count;
int ans=0;
for (i=1;i<=n;i++)
{
count=1;
max=min=a[i];
for (j=i+1;j<=n;j++)
{
if (a[j]>max)
max=a[j];
if (a[j]<min)
min=a[j];
 
if (max-min>k) break;  //很重要的一个剪枝
else 
count++;
}
if (ans<count)
ans=count;


}


 
printf("%d\n",ans);






}
return 0;

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值