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

Live Demo

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