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

Master LeetCode problem 1509 (Minimum Difference Between Largest and Smallest Value in Three Moves), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

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

Problem Explanation

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)

Solution Code

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;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1509 (Minimum Difference Between Largest and Smallest Value in Three Moves)?

This page provides optimized solutions for LeetCode problem 1509 (Minimum Difference Between Largest and Smallest Value in Three Moves) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1509 (Minimum Difference Between Largest and Smallest Value in Three Moves)?

The time complexity for LeetCode 1509 (Minimum Difference Between Largest and Smallest Value in Three Moves) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1509 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1509 in Java, C++, or Python.

Back to LeetCode Solutions