cswork / OAOpen practice workspace

The D. E. Shaw GroupOA #1

Subarray Removal

Estimated HardJudge-ready

Topics (AI-labelled)Two PointersBinary Search

Given an integer array arr of length n, count the subarrays (contiguous segments, distinguished by position) whose removal leaves an array that is non-empty and sorted in non-decreasing order (adjacent elements may be equal).

Input

The first line contains an integer n; the second line contains n integers arr[0..n−1]. 1≤n≤200000, 1≤arr[i]≤10^9.

Output

Output one integer: the number of subarrays that satisfy the condition.

Example 1

Input:

4
1 2 1 2

Output:

7

Example 2

Input:

3
3 1 2

Output:

3

Example 3

Input:

6
1 2 2 6 1 3

Output:

10

Example notes

Example 1: arr=[1,2,1,2] has 10 subarrays. The 7 removals that leave [1,2], [2], [1,1,2], [1,2], [1], [1,2,2], and [1,2] satisfy the condition; removing [1] leaves [2,1,2] and removing the last [2] leaves [1,2,1], neither of which is sorted, and removing the whole array leaves an empty array, which also fails. Example 2: removing [3], [3,1], or [1,2] satisfies the condition, so the answer is 3. Example 3: the qualifying subarrays are [1,2,2,6], [1,2,2,6,1], [2,2,6], [2,2,6,1], [2,2,6,1,3], [2,6,1], [2,6,1,3], [6,1], [6,1,3], and [1,3], so the answer is 10.

Editorial

Loading solution…