#C3369. Minimum Trimming Operations to Achieve a Non-decreasing Array

    ID: 46788 Type: Default 1000ms 256MiB

Minimum Trimming Operations to Achieve a Non-decreasing Array

Minimum Trimming Operations to Achieve a Non-decreasing Array

You are given an array of integers P of length N. Your task is to perform a series of trimming operations to transform the array into a non-decreasing sequence.

A trimming operation is defined as follows: if at any index i (with 1 ≤ i < N) the condition \[ P_{i-1} > P_i \] holds, then you can trim the element at index i-1 by setting \[ P_{i-1} = P_i \] provided that i is not the last index and also Pi is less than Pi+1 (if it exists). If a violation occurs at the last element or the condition does not allow a valid trim, then it is impossible to obtain a non-decreasing array.

Your goal is to compute the minimum number of trimming operations required to achieve a non-decreasing array. If it is impossible, output -1.

Note: A single element array is always non-decreasing.

inputFormat

The input is read from stdin and has the following format:

T
N₁
P₁ P₂ ... Pₙ₁
N₂
P₁ P₂ ... Pₙ₂
...
Nₜ
P₁ P₂ ... Pₙₜ

Here, T is the number of test cases. For each test case, the first line contains an integer N (the number of elements in the array), followed by a line of N space-separated integers representing the array P.

outputFormat

For each test case, output a single integer on a new line which is the minimum number of trimming operations required to transform the array into a non-decreasing sequence. If it is impossible, output -1.

The output should be written to stdout.

## sample
5
7
3 4 2 5 4 5 6
5
1 2 3 4 5
5
3 3 2 2 2
4
1 3 2 4
1
2
2

0 -1 1 0

</p>