Description
Given an array nums, you are allowed to choose one element of nums and change it by any value in one move.
Return the minimum difference between the largest and smallest value of nums after perfoming at most 3 moves.
Example 1:
Input: nums = [5,3,2,4]
Output: 0
Explanation: Change the array [5,3,2,4] to [2,2,2,2].
The difference between the maximum and minimum is 2-2 = 0.
Example 2:
Input: nums = [1,5,0,10,14]
Output: 1
Explanation: Change the array [1,5,0,10,14] to [1,1,0,1,1].
The difference between the maximum and minimum is 1-0 = 1.
Example 3:
Input: nums = [6,6,0,1,1,4,6]
Output: 2
Example 4:
Input: nums = [1,5,6,14,15]
Output: 1
Constraints:
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
分析
题目的意思是:给你一个数组,要求把其中至多三个数变换成任意的数,求剩下数组的最大值和最小值的差值的最小值。这道题是找规律题目,可以看成是一个数组里面移除3个数以后,剩下的数求最大最小值的差,一般集中在数组的最左边或者最右边,或者两边。如果能够发现这个,就好办了,写个循环把我说的三种情况求出来就是答案了。
代码
class Solution:
def minDifference(self, nums: List[int]) -> int:
nums.sort()
n=len(nums)
if(n<5):
return 0
l=float('inf')
for i in range(4):
t=nums[n-(3-i+1)]-nums[i]
l=min(t,l)
return l