For an array a[n], and sum(a[i]|i=0..n-1) mod n == 0. There is an operation, which can set a[i] to a[i]-1, meanwhile, a[i-1] to a[i-1]+1 or a[i+1] to a[i+1]+1.
Problem 1: How many operations do you need to make every a[i] equal to the average value?
Problem 2: If the array is cyclic, what's the result?
----------------------------------------------------------------------
For problem 1,
We could define c[i] as Sum[a[k] | k = 0..i] - avg*(i + 1), so
res = abs(c[0]) + abs(c[1]) +...+abs(c[n-1])
For problem 2,
I could only find the O(n^2) solution, but a friend give me a O(n) Solution, like this:
\
So, t[i] stands for the number transferred from a[i] to a[i-1], so
t[1]-t[0] = avg - a[0]
t[2]-t[1] = avg - a[1]
....
t[n-1]-t[n-2] = avg - a[n-2]
So t[i] = avg*i - Sum(a[0..i-1])+t[0] = t[0] + c[i-1]
What we need to do is
Minimize {abs(t[0])+abs(t[1])+....abs(t[n-1])} = Minimize{abs(t[0])+abs(t[0]+c[0])+...abs(t[0]+c[n-2])}
We could get every c in advance, O(n)
So the problem is what is the value of t[0] to make the sum of abs minimization?