#1509

Minimum Difference Between Largest and Smallest Value in Three Moves

Medium
ArrayGreedySortingSortingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(1)
💡

Intuition

Time O(n log n)Space O(1)

The optimal approach leverages sorting and focuses on the largest and smallest values in the array. By removing the three largest or three smallest values, we can quickly determine the minimum difference.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the array.
  2. 2Step 2: Calculate the minimum difference by considering the scenarios of removing up to three largest or smallest values.
  3. 3Step 3: Return the minimum of these differences.
solution.py8 lines
1# Full working Python code
2
3def minDifference(nums):
4    nums.sort()
5    n = len(nums)
6    if n <= 4:
7        return 0
8    return min(nums[n-1] - nums[3], nums[n-2] - nums[2], nums[n-3] - nums[1], nums[n-4] - nums[0])

Complexity note: The sorting step dominates the time complexity, making it O(n log n). The space complexity is O(1) as we are not using any additional data structures.

  • 1The minimum difference can be achieved by focusing on the extremes of the sorted array.
  • 2Sorting the array allows us to efficiently find the smallest and largest values to manipulate.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.