AmazonOA #315
Number of Well Performing Groups
Estimated MediumJudge-ready
Topics (AI-labelled)Two PointersStacks & Heaps
Every non-empty contiguous subarray is a group, and a group performs well if its maximum minus its minimum is exactly k. Groups with different start or end positions are different, even if their values are the same. Find the total number of well-performing groups.
Input
The first line contains n k and the second line contains the array. On this site 1≤n≤200000, −10^9≤a[i]≤10^9, −2000000000≤k≤2000000000. A negative k naturally has no valid groups and is not excluded.
Output
Output a single integer, the answer.
Example 1
Input:
3 2
2 4 6
Output:
2
Example 2
Input:
3 0
2 2 2
Output:
6
Example 3
Input:
1 -1
1
Output:
0
Example notes
The answers are 2, 6 and 0. In the second example all 6 non-empty subarrays count, so you cannot add only 1 per right end.
Editorial
Loading solution…