- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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

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

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

- Related Questions & Answers
- Program to find k-sized list where difference between largest and smallest item is minimum in Python
- C++ program to find minimum possible difference of largest and smallest of crackers
- Python program to find Largest, Smallest, Second Largest, and Second Smallest in a List?
- C# program to find Largest, Smallest, Second Largest, Second Smallest in a List
- Java program to find Largest, Smallest, Second Largest, Second Smallest in an array
- Program to find minimum moves to make array complementary in Python
- How to Find the Largest Among Three Numbers using Python?
- C++ Program to find minimum difference between strongest and weakest
- Program to find largest product of three unique items in Python
- Program to find largest of three numbers - JavaScript
- Program to find out the minimum moves in a snakes and ladders game in Python
- Python Program To Find the Smallest and Largest Elements in the Binary Search Tree
- Program to find Smallest and Largest Word in a String in C++
- Java program to find smallest of the three numbers using ternary operators
- Program to find minimum difference of max and mins after updating elements at most three times in Python

Advertisements