Counting the number of intervals

4.3

18 votes
Advanced Data Structures, Data Structures, Medium, Segment Trees
Problem

You are given a sequence of N integers a1,a2,,aN and an integer K. Your task is to count the number of intervals [l,r] such that al+ar+min(al,al+1,,ar)K.

Input format

  • First line: Two space-separated integers N,K
  • Second line: N space-separated integers denoting the elements of the sequence

Output format

  • Print the answer in a single line.

Constraints

1N5×105,  80% test cases N2×105

1K1018

1ai1018

 

Sample Input
5 6
1 2 3 4 5

Sample Output
5
Time Limit: 3
Memory Limit: 512
Source Limit:
Explanation

There are five intervals satisfy the condition:

  • [1, 1]: a1+min(a1)+a1=3
  • [1, 2]: a1+min(a1,a2)+a2=4
  • [1, 3]: a1+min(a1,a2,a3)+a3=5
  • [1, 4]: a1+min(a1,a2,a3,a4)+a4=6
  • [2, 2]: a2+min(a2,a2)+a2=6
Editor Image

?