LeetCode 1509: Minimum Difference Between Largest and Smallest Value in Three Moves

ArrayGreedySorting

Problem Description

Explanation:

To minimize the difference between the largest and smallest values after performing at most three moves, we need to consider various scenarios. One approach is to sort the array and then try different combinations of changing up to three elements to find the smallest difference.

  1. Sort the array.
  2. Initialize a variable to keep track of the minimum difference.
  3. Try the following scenarios:
    • Keep the smallest 3 and largest 0 elements unchanged.
    • Change one element from each side (left and right).
    • Change two elements from one side and one from the other side.
    • Change three elements from one side.
  4. Calculate the difference for each scenario and update the minimum difference.

Time Complexity: O(n log n) where n is the number of elements in the array due to sorting. Space Complexity: O(1)

Solutions

import java.util.Arrays;

class Solution {
    public int minDifference(int[] nums) {
        int n = nums.length;
        if (n <= 4) return 0;

        Arrays.sort(nums);

        int minDiff = Integer.MAX_VALUE;

        for (int i = 0; i <= 3; i++) {
            minDiff = Math.min(minDiff, nums[n - 4 + i] - nums[i]);
        }

        return minDiff;
    }
}

Loading editor...