[leetcode] 910. Smallest Range II

网友投稿 236 2022-09-15

[leetcode] 910. Smallest Range II

Description

Given an array A of integers, for each integer A[i] we need to choose either x = -K or x = K, and add x to A[i] (only once).

After this process, we have some array B.

Return the smallest possible difference between the maximum value of B and the minimum value of B.

Example 1:

Input: A = [1], K = 0Output: 0Explanation: B = [1]

Example 2:

Input: A = [0,10], K = 2Output: 6Explanation: B = [2,8]

Example 3:

Input: A = [1,3,6], K = 3Output: 3Explanation: B = [4,6,3]

Note:

1 <= A.length <= 100000 <= A[i] <= 100000 <= K <= 10000

分析

题目的意思是:给定一个数组,每个数可以加K,或者可以减K。对于排序好的数组A,如果 A[i] < A[j],我们只需要考虑(A[i] + K, A[j] - K)的情况,其他情况求出来的差值肯定比这个大。那么最终我们只需要考虑 A[0] + K, A[i] + K, A[i+1] - K, A[- 1] - K 就是计算结果的唯一值。其中A[0]是数组的最小值,A[-1]是数组的最大值,弄懂了这个,然后遍历一遍就完了。

代码

class Solution: def smallestRangeII(self, A: List[int], K: int) -> int: A.sort() n=len(A) res=A[-1]-A[0] for i in range(n-1): t1=max(A[-1]-K,A[i]+K) t2=min(A[0]+K,A[i+1]-K) res=min(res,t1-t2) return res

参考文献

​​最小差值 II​​

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:私域流量运营,你的朋友圈,应该这样发!
下一篇:[leetcode] 1679. Max Number of K-Sum Pairs
相关文章

 发表评论

暂时没有评论,来抢沙发吧~