- Egocentric Subarrays
inputstandard input
outputstandard output
You have an array a consisting of n positive integers, and an integer k.
You call a subarray an egocentric subarray if the difference between the maximum and minimum elements of the subarray is equal to k.
Recall that a subarray is a contiguous segment of elements of the original array, in order.
For example, if a=[5,4,1,2,3,6] and k=3, then [4,1], [4,1,2,3], and [3,6] are egocentric subarrays, while [5,4,1,2], [4,1,2,3,6], and [5] are not.
Your task is to find the number of egocentric subarrays in the array.
Input
The first line of input contains two space-separated integers n (1<=n<=100) and k (1<=k<=109): the length of the array, and the number to find if the difference is equal to, respectively.
The next line consists of n space-separated integers: the array elements (1<=ai<=109).
Output
Output the number of egocentric subarrays of the array.
Scoring
Full problem: 7 Points
translation:
- Egocentric substring time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard output You have an array a consisting of n positive integers and an integer k.
If the difference between the largest and smallest elements of a sub-array is equal to k, you can call it a self-centered sub-array. Recall that the sub-array is a continuous segment of the elements of the original array.
For example, if a=[5,4,1,2,3,6] and
k=3, then [4,1,2,3], and [3,6] are self-centered subarrays, and [5, 4,1,2,6], and [5] are not.
Your task is to find the number of egocentric subarrays in the array. The first line of input contains two integers n (1<=n<=100) and k
(1<=k<=109) separated by spaces : the length of the array, and the number to find whether the difference is equal.
The next line consists of n integers separated by spaces: array elements (1<=ai<=109). Output the number of self-centered sub-arrays in the output array. Score
Complete questions: 7 points
Ideas:
This is a bit of a three-layer loop. The outer layer uses size to control the scale of the problem. The second layer controls the start. The third layer finds the current sub-problems max and min. At the end of the third layer, it is judged whether max-min == k. ans++;
finally output ans!
ac code(7points):
#include<stdio.h>
int main()
{
int n,k;
scanf("%d %d",&n,&k);
int a[n];
for(int i=0;i<n;i++){
scanf("%d",&a[i]);
}
int ans=0;
int size;
for(size=2;size<=n;size++){
for(int i=0;i<=n-size;i++){
int min=a[i];
int max=a[i];
for(int j=i;j<i+size;j++){
if(max<a[j])max=a[j];
if(min>a[j])min=a[j];
}
if(max-min==k)ans++;
}
}
printf("%d\n",ans);
return 0;
}