Moving Stones Until Consecutive II - Problem

There are some stones in different positions on the X-axis. You are given an integer array stones where stones[i] represents the position of the i-th stone.

Call a stone an endpoint stone if it has the smallest or largest position. In one move, you pick up an endpoint stone and move it to an unoccupied position so that it is no longer an endpoint stone.

For example, if the stones are at positions [1,2,5], you cannot move the endpoint stone at position 5 to position 3 or 4 because it would still be an endpoint stone.

The game ends when you cannot make any more moves (i.e., the stones are in consecutive positions). Return an integer array answer of length 2 where:

  • answer[0] is the minimum number of moves you can play
  • answer[1] is the maximum number of moves you can play

Input & Output

Example 1 — Basic Case
$ Input: stones = [7,4,9]
Output: [1,2]
💡 Note: We can move 4 to 8 to get [7,8,9] in 1 move (minimum). For maximum, we can move 4 to 6, then 7 to 8 to get [6,8,9] then [8,9,10], taking 2 moves total.
Example 2 — Already Consecutive
$ Input: stones = [6,5,4,3,10]
Output: [2,3]
💡 Note: For minimum: move 3 to 7 and 10 to 8 to get [4,5,6,7,8]. For maximum: avoid the larger gap by keeping either [3,4,5,6] or [5,6,7,8,9,10] pattern.
Example 3 — Large Gaps
$ Input: stones = [1,3,8]
Output: [1,2]
💡 Note: Minimum: move 1 to 7 to get [3,7,8], then move endpoint to make consecutive. Maximum: move 8 to 2, then 3 to get larger sequence.

Constraints

  • 3 ≤ stones.length ≤ 104
  • 1 ≤ stones[i] ≤ 109

Visualization

Tap to expand
Moving Stones Until Consecutive II INPUT 4 5 6 7 8 9 4 7 9 Stones on X-axis Input Array: 7 4 9 stones = [7, 4, 9] endpoint endpoint Sorted: [4, 7, 9] n = 3 stones Range: 4 to 9 ALGORITHM STEPS 1 Sort Stones [7,4,9] --> [4,7,9] 2 Calc Max Moves Total gaps - min endpoint gap max((9-4+1-3)-(9-7-1), (9-4+1-3)-(7-4-1)) = 2 3 Calc Min Moves Sliding window of size n Find window with most stones min = n - maxInWindow = 1 4 Special Cases Check consecutive stones with one gap at end Window size=3 Gaps=2 FINAL RESULT Minimum Moves: Move stone 4 to 8 7 8 9 1 move: [7,8,9] Maximum Moves: 2 moves total Move 1: 4 --> 6 Move 2: 9 --> 8 Final: [6,7,8] Output: [1, 2] OK - Verified Key Insight: For MAXIMUM moves: Count empty spaces between endpoints, subtract minimum endpoint gap. For MINIMUM moves: Use sliding window of size n to find position with most existing stones. Moves needed = n - (stones already in optimal window). Handle special case of consecutive stones. TutorialsPoint - Moving Stones Until Consecutive II | Mathematical Analysis Approach
Asked in
Google 15 Amazon 12 Facebook 8
18.8K Views
Medium Frequency
~35 min Avg. Time
425 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen