Little Shino and Pairs

3.9

90 votes
Approved, Data Structures, Easy, Stacks
Problem

Given a permutation of number from 1 to N. Among all the subarrays, find the number of unique pairs (a,b) such that ab and a is maximum and b is second maximum in that subarray.

Input:
First line contains an integer, N (1N105). Second line contains N space separated distinct integers, Ai (1AiN), denoting the permutation.

Output:
Print the required answer.

Sample Input
5
1 2 3 4 5
Sample Output
4
Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

All the possible subarrays are:

1
12
123
1234
12345
2
23
234
2345
3
34
345
4
45
5

The 4 unique pairs are:
(2,1)
(3,2)
(4,3)
(5,4)

Editor Image

?