##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
##### ###### ##### ### # # ### # # ###### ## ## ## ## ## ## ## # # # # # ## ##### #### ##### # # # # # # # #### ## # ## ## ## ## # # # # # ## ## # ###### ## ### # ### # ######
First assume the board contains exactly kings. We want to assign each diagonal cell to a distinct king, and move each king there.
For a king starting at , the minimum number of moves to reach (ignoring other kings) is , because in one move both coordinates can change by at most .
Let be two diagonal indices, and let , be two kings with . Then it is never worse to match and than to match and .
This means there exists an optimal assignment where, after sorting kings by , the matched diagonal indices are nondecreasing. In the special case of exactly kings, the optimal assignment is simply: the -th king in sorted order is matched to diagonal cell . So the answer becomes after sorting by .