##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
We can apply operations: choose , do a[i-1]-- and a[i]++.
Equivalently, we move unit of value one step to the right, inside .
Define . We want to make for all in .
Key invariant (total sum): The operation preserves , so it preserves .
To end with all zeros we must have: .
Key invariant (interval prefix sums can only go down): For in , define interval-prefix: .
If we apply the operation at index , only decreases and increases. So among all , the only one that changes is , and it decreases by . No can ever increase.
In the target state (all ), every equals . Since never increases during operations, we must start with:
for all ,
and also (from total sum): .
So a necessary condition is:
This condition is also sufficient: Process positions from left to right. At position , if , we can move this surplus right (using operations at repeatedly) to reduce to . The constraints guarantee we never need to “pull” from the right (which is impossible), so we can finish and reach all zeros.
Conclusion: is beautiful ⇔ all interval prefix sums of are nonnegative and the total is zero.