PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000074. Dãy hình kim tự tháp (Pyramid Array)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Dãy hình kim tự tháp (Pyramid Array)

Pyramid Array

Source: CSES

Version: Phuoc Hung OJ Extended

Problem Statement

You are given an array of nn pairwise distinct integers. In one operation, you may swap two adjacent elements, at a cost of one move.

An array is a pyramid array if it has a peak, is strictly increasing before the peak, and is strictly decreasing after the peak. The peak may be the first or last element; a fully increasing or fully decreasing array is also valid.

Determine the minimum number of adjacent swaps needed to obtain a pyramid array. You do not need to print the final arrangement.

Input

The first line contains the array length nn.

The second line contains nn pairwise distinct integers a1,a2,…,ana_1,a_2,\ldots,a_n.

Output

Print one integer: the minimum number of adjacent swaps to form a pyramid array.

Subtasks

  • Subtask 1 (20 points): 1≤n≤81\le n\le 8; 1≤ai≤1091\le a_i\le 10^9 for every 1≤i≤n1\le i\le n; all values are pairwise distinct.

  • Subtask 2 (30 points): 1≤n≤20001\le n\le 2000; 1≤ai≤1091\le a_i\le 10^9 for every 1≤i≤n1\le i\le n; all values are pairwise distinct.

  • Subtask 3 (50 points): 1≤n≤2000001\le n\le 200000; 1≤ai≤1091\le a_i\le 10^9 for every 1≤i≤n1\le i\le n; all values are pairwise distinct.

Examples

Input

4
2 1 5 3

Output

1

Explanation

Initially [2,1,5,3][2,1,5,3] is not a pyramid: it decreases from 22 to 11, then increases to 55. Swap the adjacent values 22 and 11 once, obtaining [1,2,5,3][1,2,5,3].

Now 1<2<51<2<5 up to peak 55, followed by 5>35>3. The new array is a pyramid. Zero swaps cannot suffice because the initial array was invalid, so one swap is optimal. Print 1.