Up and Down Sequence
InterviewTime limit5sMemory limit512 MB
Count the fewest adjacent swaps that turn distinct numbers into a sequence that rises to one peak and then falls.
- Level
Medium5 of 10
- Topics
- Brute force, Sorting
- Solved
- No attempts yet
Problem
You are given a sequence of distinct integers. Rearrange it into an up and down sequence, that is, a sequence satisfying for some index with . The values increase up to one position and decrease after it.
Only one operation is allowed. You may swap two adjacent elements of the sequence. Find the minimum number of such swaps needed to reach an up and down sequence.
Input
The first line contains the number of test cases . test cases follow. The first line of each test case contains the integer , and the second line contains distinct integers separated by spaces.
Limits
- The are pairwise distinct.
Output
For each test case, print one line in the form Case #x: y, where is the test case number starting from 1 and is the minimum number of adjacent swaps needed to rearrange into an up and down sequence.
Hint
In the first case of the sample, the sequence is already up and down (with ), so no swap is needed. In the second case, swapping 3 and 7 gives 1 8 10 7 3, which is up and down with .