1410. King Gathering Cost
Chess kings stand on an unbounded board at the cells listed in kings, each entry [x, y]. A king moves one step per turn to any of its 8 neighbouring cells, and several kings may share a cell. Choose a single integer cell where all kings meet so that the total number of moves, summed over all kings, is as small as possible, and return that minimum total as a long.
A king needs max(|dx|, |dy|) moves. Rotate with u = x + y and v = x - y, so each distance becomes (|du| + |dv|) / 2 and the cell must satisfy u = v (mod 2). Take the median of u and the median of v; if their parities differ, also try shifting one of them by 1 in either direction and keep the cheapest. The intended solution runs in O(n log n) time and O(n) space.
Example 1
- Input:
- kings = [[0,0]]
- Output:
- 0
- Explanation:
A single king is already home, so no moves are needed.
Example 2
- Input:
- kings = [[0,0],[4,0]]
- Output:
- 4
- Explanation:
Any cell on the row between them costs 4 moves in total, for example the cell (2, 0).
Example 3
- Input:
- kings = [[0,0],[1,0],[0,1],[1,1]]
- Output:
- 3
- Explanation:
Meeting on any of the four occupied cells costs 0 + 1 + 1 + 1 = 3, and nothing cheaper exists.
Constraints
1 ≤ n ≤ 105
-109 ≤ x, y ≤ 109
The answer can exceed 32 bits.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 7,200 msC++ 1,800 msJava 3,600 msJavaScript 3,600 msTypeScript 3,600 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)