Skip to content

1509. Minimum Difference Between Largest and Smallest Value in Three Moves 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int minDifference(vector<int>& nums) {
    const int n = nums.size();
    if (n < 5)
      return 0;

    int ans = INT_MAX;

    ranges::sort(nums);

    // 1. Change nums[0..i) to nums[i].
    // 2. Change nums[n - 3 + i..n) to nums[n - 4 + i].
    for (int i = 0; i <= 3; ++i)
      ans = min(ans, nums[n - 4 + i] - nums[i]);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int minDifference(int[] nums) {
    final int n = nums.length;
    if (n < 5)
      return 0;

    int ans = Integer.MAX_VALUE;

    Arrays.sort(nums);

    // 1. Change nums[0..i) to nums[i].
    // 2. Change nums[n - 3 + i..n) to nums[n - 4 + i].
    for (int i = 0; i <= 3; ++i)
      ans = Math.min(ans, nums[n - 4 + i] - nums[i]);

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def minDifference(self, nums: list[int]) -> int:
    n = len(nums)
    if n < 5:
      return 0

    ans = math.inf

    nums.sort()

    # 1. Change nums[0..i) to nums[i].
    # 2. Change nums[n - 3 + i..n) to nums[n - 4 + i].
    for i in range(4):
      ans = min(ans, nums[n - 4 + i] - nums[i])

    return ans