Official algorithmic problem description and constraints.
A circular array π
of length π
is nice if every element has at least one adjacent element
β
that is equal to it. Formally, for every 1β€πβ€π
, at least one of the following holds: π
π
=π
(π+πβ2)modπ+1
, or π
π
=π
πmodπ+1
, where π₯modπ¦
denotes the remainder from dividing π₯
by π¦
.
You are given a circular array π
of length π
. In one operation, you may increase or decrease any element of π
by 1
. Your task is to determine the minimum number of operations required to make array π
nice. More formally, find the minimum value of β
π
π=1
|π
π
βπ
π
|
among all nice circular arrays π
of length π
.
β
In a circular array of length π
:
Input
Each test contains multiple test cases. The first line contains the number of test cases π‘
(1β€π‘β€10
4
). The description of the test cases follows.
The first line of each test case contains a single integer π
(3β€πβ€2β 10
5
) β the length of the circular array π
.
The second line of each test case contains π
integers π
1
,π
2
,β¦,π
π
(1β€π
π
β€10
9
) β the elements of the circular array π
.
It is guaranteed that the sum of π
over all test cases does not exceed 2β 10
5
.
Output
For each test case, output a single integer representing the minimum number of operations required to make array π
nice.
Example
Input
Copy
4 5 1 1 1 1 1 4 2 100 99 3 5 2 2 5 9 5 6 1 1 1 2 1 2
Output
Copy
0 2 4 1
Note
In the first test case, all elements of π
are equal. Therefore, the circular array π
is already nice and no operations are required.
In the second test case, we can perform the following sequence of operations:
After these operations, every element has at least one adjacent element with the same value:
In the third test case, the circular array π
can become nice by decreasing π
4
four times. This results in π=[2,2,5,5,5]
which is nice as every element has at least one adjacent element with the same value.
Detailed video explanations, mathematical intuition, and clean C++ implementation code.