Problem Description
Given three stones placed at distinct positions on the X-axis, determine the minimum and maximum number of moves needed such that the stones are in three consecutive positions. In each move, you can move a stone that is at one of the endpoints (either the lowest or highest positioned stone) to a new position between the current endpoints, provided that the new position is not already occupied by the middle stone.
Key Insights
- Sort the three positions to simplify the gap calculations.
- The game ends when the stones are in consecutive positions (i.e., the difference between adjacent stones is 1).
- The minimum moves have special cases:
- 0 moves if the stones are already consecutive.
- 1 move if there is a gap of exactly 2 between any two stones.
- Otherwise, 2 moves are required.
- The maximum moves is computed by taking the larger gap between the two pairs (left gap and right gap) minus 1.
Space and Time Complexity
Time Complexity: O(1) - The solution only involves a few arithmetic operations. Space Complexity: O(1) - A constant amount of extra space is used.
Solution
The approach begins by sorting the positions of the three stones to obtain x, y, and z where x < y < z. Two primary cases are considered for minimum moves:
- If the stones are already consecutive (gaps of 1), no moves are needed.
- If one gap is exactly 2, then a single move is sufficient because the stone can be moved to fill the gap.
- Otherwise, the answer for minimum moves is 2.
For the maximum number of moves, the key observation is that each move reduces one of the larger gaps by one position. Thus, the maximum moves are equal to the larger gap (either between x and y or between y and z) minus 1.
This solution uses simple sorting and arithmetic to achieve optimal performance.