- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions

# 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 Articles
- 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?
- Program to find minimum moves to make array complementary in Python
- 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
- Python Program To Find the Smallest and Largest Elements in the Binary Search Tree
- Python Program to Find the Largest value in a Tree using Inorder Traversal
- Program to find out the minimum moves in a snakes and ladders game in Python
- Program to find largest product of three unique items in Python
- How to Find the Largest Among Three Numbers using Python?
- Program to find Smallest and Largest Word in a String in C++
- Program to find minimum difference between two elements from two lists in Python
- C++ Program to find minimum difference between strongest and weakest
- Program to find minimum difference of max and mins after updating elements at most three times in Python

Advertisements