E is climbing a multi-level gyroscopic tower with $$$n$$$ circular levels. There is a rare musical note at the top of the tower she wants to obtain. Each $$$i$$$th level can rotate independently, and has a known starting angle $$$a_i$$$ (measured in degrees starting from the North, where $$$0^\circ \leq a_i \lt 360^\circ$$$).
E starts at the bottom level, and can only climb to the next level after aligning her current level. We say a level has been aligned when the angle of the level matches the angle of all levels below it, either by moving it clockwise or counterclockwise (which is trivially satisfied if it is the bottom level). Furthermore,
E is lazy, and wants to reach the top of the tower with minimum effort. Please help her determine the fewest total degrees of rotation needed to align all levels of the tower.
The first line contains an integer $$$n$$$ ($$$1 \leq n \leq 10^3$$$), the number of levels in the tower.
The next line contains $$$n$$$ integers, $$$a_1,a_2,\cdots, a_n$$$ for $$$0 \leq a_i \lt 360$$$.
Please output the fewest total degrees of rotation needed to align all levels of the tower.
34 6 270
266
1418 291 230 140 24 293 29 53 359 20 1 39 200 49
1386
In the first sample test case, rotating all levels to exactly 6$$$^\circ$$$ from North gives $$$|4-6| + |6-6| + |270-6|$$$ = 266 degrees, which is also the minimum possible degrees of rotation.