All problems

Problem 821

Count Number of Teams

Medium · 20 pts · Array, Dynamic Programming

Problem

Soldiers stand in a line with distinct ratings. A team is three soldiers at positions i < j < k whose ratings are strictly increasing or strictly decreasing. Count the possible teams. Treat each soldier as the middle one: if L1 soldiers to the left are smaller and R2 to the right are larger, they form L1 × R2 increasing teams, and similarly with larger on the left and smaller on the right for decreasing ones.

Input

The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1]. All values are distinct.

Output

Print the number of valid teams.

Constraints

3 <= N <= 1000; 1 <= A[i] <= 10^5; values are distinct

Example input

5
2 5 3 4 1

Example output

3

Explanation

For ratings 2 5 3 4 1, the teams are (2,3,4), (5,4,1) and (5,3,1). So the answer is 3.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Longest Continuous Increasing Subsequence Next: Minimum Value to Get Positive Step by Step Sum