- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 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
Advertisements