B. Nastya and Door ( Round #637 Div. 2)前缀和

在这里插入图片描述
在这里插入图片描述
Note
In the first example, you need to select a segment of mountains from 2 to 7. In this segment, the indexes 3 and 6 are peaks, so the answer is 3 (only 2 peaks, so the door will break into 3 parts). It is not difficult to notice that the mountain segments [1,6] and [3,8] are not suitable since they only have a 1 peak (for the first segment, the 6 index is not a peak, and for the second segment, the 3 index is not a peak).

In the second example, you need to select a segment of mountains from 2 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts).

In the third example, you need to select a segment of mountains from 1 to 4. In this segment, the index 3 is a peak, so the answer is 2 (only 1 peak, so the door will break into 2 parts). You can see that on the segments [2,5], [4,7] and [5,8] the number of peaks is also 1, but these segments have a left border greater than the segment [1,4], so they are not the correct answer.

思路:这道题用到了前缀和,因为我们要在区间为k的地方找到尽可能多的山顶,所以首先就是把山顶找出来,在每个长度k的区间统计其中山顶的数量,在每个长度为k的地方肯定不能用循环去统计其中山顶的数量,所以就用到了前缀和.
长度为k的区间中山顶的数量 cnt = c[i+k-2]-c[i],然后就可以找到最大的数量。

#include<bits/stdc++.h>
using namespace std;
#define  maxn 200005
int a[maxn];
int c[maxn];
int main()
{
    int t ;
    cin>>t;
    while(t--)
    {
        int count1 = 0;
        int n,k;
        cin>>n>>k;
        for(int i=1; i<=n; i++){
            cin>>a[i];
        }
        for(int i=1; i<=n; i++){
            if(a[i]>a[i-1]&&a[i]>a[i+1]){
                count1++;
            }
            c[i]=count1;
        }
        int max1 = 0,pos = 1;
        for(int i=1; i<=n-k+1; i++){
            int cnt = c[i+k-2]-c[i];
            if(cnt>max1){
                max1 = cnt ;
                pos = i;
            }
        }
        cout<<max1+1<<" "<<pos<<endl;
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值