MathLabs

Problem 5

nn people are seated in a circle. A total of nknk coins are distributed among them, not necessarily equally. A move transfers one coin between two adjacent people. Find an algorithm using the minimum number of moves that leaves everyone with the same number of coins.
Step 2 of 5: Define the prefix-sum potential
X=∑i=1n−1∣∑j=1idj∣X=\sum_{i=1}^{n-1}\left|\sum_{j=1}^id_j\right|
Detailed analysis

Set X=∑i=1n−1∣d1+⋯+di∣X=\sum_{i=1}^{n-1}|d_1+\cdots+d_i|. It is zero exactly when all did_i are zero. A move across edge i,i+1i,i+1 for i<ni<n changes only the iith prefix sum, and hence changes XX by one.