
- 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 of max and mins after updating elements at most three times in Python
Suppose we have a list of numbers called nums, now consider an operation where we can update an element to any value. We can perform at most 3 of such operations, we have to find the resulting minimum difference between the max and the min value in nums.
So, if the input is like nums = [2, 3, 4, 5, 6, 7], then the output will be 2, as we can change the list to [4, 3, 4, 5, 4, 4] and then 5 - 3 = 2.
To solve this, we will follow these steps −
- if size of nums <= 4, then
- return 0
- n := size of nums
- sort the list nums
- return minimum of the difference between nums[n-4 + i] - nums[i] for all i in range 0 to 3
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, nums): if len(nums) <= 4: return 0 nums.sort() return min(nums[-4 + i] - nums[i] for i in range(4)) ob = Solution() nums = [2, 3, 4, 5, 6, 7] print(ob.solve(nums))
Input
[2, 3, 4, 5, 6, 7]
Output
2
- Related Articles
- Program to find maximum profit after buying and selling stocks at most two times in python
- Program to find minimum possible integer after at most k adjacent swaps on digits in Python
- Program to find minimum amplitude after deleting K elements in Python
- Program to find minimum possible difference of indices of adjacent elements in Python
- Program to find number of sequences after adjacent k swaps and at most k swaps in Python
- Program to find minimum difference between largest and smallest value in three moves using Python
- Program to find minimum cost to reach final index with at most k steps in python
- Program to find minimum difference between two elements from two lists in Python
- Program to find min length of run-length encoding after removing at most k characters in Python
- Program to find most occurring number after k increments in python
- Program to find minimum number colors remain after merging in Python
- Program to find minimum amplitude after deleting KLength sublist in Python
- Program to find minimum length of string after deleting similar ends in Python
- Program to find minimum absolute sum difference in Python
- Program to find elements from list which have occurred at least k times in Python

Advertisements