Skip to main content
Back to problems
#1040
Medium Algorithms

Moving stones until consecutive ii

Array Math Sliding Window Sorting
58.8% acceptance
Feb 25, 2026
406
754
There are some stones in different positions on the X-axis. You are given an integer array stones, the positions of the stones. 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. In particular, if the stones are at say, stones = [1,2,5], you cannot move the endpoint stone at position 5, since moving it to any position (such as 0, or 3) will still keep that stone as an endpoint stone. The game ends when you cannot make any more moves (i.e., the stones are in three consecutive positions). Return an integer array answer of length 2 where: answer[0] is the minimum number of moves you can play, and answer[1] is the maximum number of moves you can play.

Solution

Rust
Time O(n²)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn num_moves_stones_ii(stones: Vec<i32>) -> Vec<i32> {
    let mut stones = stones;
    stones.sort();
    let n = stones.len();
    // max: take the better of removing left or right endpoint first
    let max_val = (stones[n-1] - stones[1] - (n as i32 - 2))
      .max(stones[n-2] - stones[0] - (n as i32 - 2));
    // min: sliding window of size n
    let mut min_val = n as i32;
    let mut j = 0usize;
    for i in 0..n {
      while j + 1 < n && stones[j+1] - stones[i] < n as i32 { j += 1; }
      let count = (j - i + 1) as i32;
      let candidate = if count == (n as i32 - 1) && stones[j] - stones[i] == n as i32 - 2 {
        2  // special case: n-1 consecutive stones, far stone needs 2 moves
      } else {
        n as i32 - count
      };
      min_val = min_val.min(candidate);
    }
    vec![min_val, max_val]
  }
}