Program to find minimum difference between largest and smallest value in three moves using Python

Given an array nums, we can change any element to any value in one move. The goal is to find the minimum difference between the largest and smallest values after performing at most 3 moves.

The strategy is to either remove the largest elements or smallest elements (or a combination) to minimize the range. Since we have 3 moves, we can consider removing 0-3 smallest and 3-0 largest elements respectively.

Algorithm

The approach works as follows ?

  • If array size ? 4, we can make all elements equal in 3 moves, so return 0

  • Sort the array to easily identify smallest and largest elements

  • Try all combinations: remove 0,1,2,3 smallest and 3,2,1,0 largest elements

  • Calculate the difference for each combination and return the minimum

Example

def solve(nums):
    if len(nums) <= 4:
        return 0
    
    nums.sort()
    ans = float("inf")
    
    # Try removing i smallest and (3-i) largest elements
    for i in range(4):
        mi = nums[i]  # New minimum after removing i smallest
        ma = nums[-(3-i+1)]  # New maximum after removing (3-i) largest
        ans = min(ma - mi, ans)
    
    return ans

nums = [3, 7, 2, 12, 16]
print(f"Original array: {nums}")
print(f"Minimum difference: {solve(nums)}")
Original array: [3, 7, 2, 12, 16]
Minimum difference: 1

How It Works

For the array [3, 7, 2, 12, 16], after sorting we get [2, 3, 7, 12, 16]. The algorithm tries these combinations ?

  • Remove 0 smallest, 3 largest: Range = [2, 3] ? difference = 1

  • Remove 1 smallest, 2 largest: Range = [3, 7] ? difference = 4

  • Remove 2 smallest, 1 largest: Range = [7, 12] ? difference = 5

  • Remove 3 smallest, 0 largest: Range = [12, 16] ? difference = 4

The minimum difference is 1, achieved by keeping elements [2, 3] and changing the rest.

Additional Example

def solve(nums):
    if len(nums) <= 4:
        return 0
    
    nums.sort()
    ans = float("inf")
    
    for i in range(4):
        mi = nums[i]
        ma = nums[-(3-i+1)]
        ans = min(ma - mi, ans)
    
    return ans

# Test with different arrays
test_cases = [
    [1, 5, 0, 10, 14],
    [1, 1, 1, 1],
    [6, 6, 0, 1, 1, 3]
]

for nums in test_cases:
    result = solve(nums)
    print(f"Array: {nums} ? Minimum difference: {result}")
Array: [1, 5, 0, 10, 14] ? Minimum difference: 1
Array: [1, 1, 1, 1] ? Minimum difference: 0
Array: [6, 6, 0, 1, 1, 3] ? Minimum difference: 2

Conclusion

This algorithm efficiently finds the minimum difference by sorting the array and trying all possible combinations of removing elements from both ends. The time complexity is O(n log n) due to sorting, making it optimal for this problem.

Updated on: 2026-03-25T20:58:37+05:30

701 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements