Moving Stones Until Consecutive II
The problem is asking us to find both the minimum and maximum number of moves required to arrange the stones in consecutive positions. Here’s an approach to solve this problem:
- Sort the Stones: First, we sort the stones to determine their relative positions.
- Calculate Maximum Moves: The maximum number of moves will be the maximum of moving the leftmost or the rightmost stones, minus the number of stones already in place.
- Calculate Minimum Moves: We’ll iterate through the stones and use a sliding window approach to calculate the minimum moves needed.
Here’s the code:
|
|
Explanation:
- Calculate Maximum Moves: The maximum number of moves is determined by moving the leftmost stones to the rightmost empty positions, or vice versa, minus the number of stones already in place.
- Sliding Window: We use a sliding window to find the minimum moves. If the current window contains
n-1
stones, and the difference between the maximum and minimum isn-2
, then it takes two moves to fill the gap. Otherwise, it will taken
minus the number of stones in the current window to make them consecutive. - Return the Result: The final result will be an array containing the minimum and maximum number of moves.
This code will handle all the constraints and provide the correct result for the given problem.