CHEFTWOS Editoral

Qstn:https://www.codechef.com/OCT16/problems/CHEFTWOS

Solution:https://discuss.codechef.com/questions/86208/cheftwos-editorial

I have read the editorial many times but I can’t understand 2nd step that is swaping (Final Solution)
can anyone help me by explaining in details.I am new to dynamic programming so please explain in detail.

Thank You