Skip to main content
Back to problems
#1509
Medium Algorithms

Minimum difference between largest and smallest value in three moves

Array Greedy Sorting
59.2% acceptance
Feb 25, 2026
2546
286
You are given an integer array nums. In one move, you can choose one element of nums and change it to any value. Return the minimum difference between the largest and smallest value of nums after performing at most three moves.

Solution

Rust
Time O(n log n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn min_difference(mut nums: Vec<i32>) -> i32 {
    let n = nums.len();
    if n <= 4 { return 0; }
    nums.sort();
    // Try removing i from left and (3-i) from right
    (0..=3).map(|i| nums[n - 1 - (3 - i)] - nums[i]).min().unwrap()
  }
}