Moving Stones Until Consecutive

We can find the minimum and maximum number of moves to bring the stones into three consecutive positions by analyzing the gaps between the sorted positions of the stones. Here’s how:

  1. Sort the Positions: Sort the positions a, b, and c, so that we work with them in ascending order.
  2. Calculate the Gaps: Find the differences between the sorted positions, namely gap1 and gap2.
  3. Minimum Moves:
    • If both gap1 and gap2 are 1, then the stones are already consecutive, and the minimum moves are 0.
    • If either gap1 or gap2 is 1, or either gap1 or gap2 is 2, the minimum moves are 1.
    • Otherwise, the minimum moves are 2.
  4. Maximum Moves: The maximum moves are the sum of gap1 - 1 and gap2 - 1, as each gap can be filled one by one.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution:
    def numMovesStones(self, a: int, b: int, c: int) -> List[int]:
        # Sort the positions
        x, y, z = sorted([a, b, c])

        # Calculate the gaps
        gap1 = y - x
        gap2 = z - y

        # Find minimum moves
        if gap1 == 1 and gap2 == 1:
            min_moves = 0
        elif gap1 <= 2 or gap2 <= 2:
            min_moves = 1
        else:
            min_moves = 2

        # Find maximum moves
        max_moves = (gap1 - 1) + (gap2 - 1)

        return [min_moves, max_moves]

Explanation:

  • Sorting the positions ensures that we are working with them in ascending order.
  • By calculating the gaps, we can determine how many positions need to be filled.
  • The minimum moves are calculated based on the size of the gaps.
  • The maximum moves are determined by the sum of the gaps minus 1 for each.

For the given example a = 1, b = 2, c = 5, the code will return [1,2], corresponding to the minimum and maximum number of moves.