Count the triangles

3.4

33 votes
Sparse Table, Advanced Data Structures, Easy-Medium, Data Structures
Problem

Given an array A of length N. We say that a subarray (Al,Al+1,,Ar) is good if for every li<j<kr we can form a triangle (possible degenerate) with lengths Ai,Aj,Ak. In particular if 0rl1 then the subarray is good. Count the number of good subarrays. 

Input

The first line contains one integer - n (1n2105).

The second line contains n integers - A1,A2,,AN (1Ai109).

Output

Output the number of good subarrays.

Time Limit: 3
Memory Limit: 256
Source Limit:
Explanation

The satisfying subarrays have (l,r){(1,1),(2,2),(3,3),(4,4),(5,5),(6,6),(1,2),(2,3),(3,4),(4,5),(5.6),(3,5)}

Editor Image

?