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