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

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

Suppose we have an array called nums. We can change one element from this array to any value in one move. We have to find the minimum difference between the largest and smallest value of nums after preforming at most 3 moves.

So, if the input is like nums = [3,7,2,12,16], then the output will be 1 because we can make given array to [1,1,0,1,1], so the maximum is 1 and minimum is 0, so the difference is 1.

To solve this, we will follow these steps −

• if size of nums <= 4, then

• return 0

• sort the list nums

• ans := infinity

• for i in range 0 to 3, do

• mi := nums[i]

• ma := nums[length of nums -(3-i+1)]

• ans := minimum of ma-mi and ans

• return ans

Let us see the following implementation to get better understanding −

## Example

Live Demo

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
nums = [3,7,2,12,16]
print(solve(nums))

## Input

[3,7,2,12,16]

## Output

1