英文原文
You are given an integer array nums and an integer k.
For each index i where 0 <= i < nums.length, change nums[i] to be either nums[i] + k or nums[i] - k.
The score of nums is the difference between the maximum and minimum elements in nums.
Return the minimum score of nums after changing the values at each index.
Example 1:
Input: nums = [1], k = 0 Output: 0 Explanation: The score is max(nums) - min(nums) = 1 - 1 = 0.
Example 2:
Input: nums = [0,10], k = 2 Output: 6 Explanation: Change nums to be [2, 8]. The score is max(nums) - min(nums) = 8 - 2 = 6.
Example 3:
Input: nums = [1,3,6], k = 3 Output: 3 Explanation: Change nums to be [4, 6, 3]. The score is max(nums) - min(nums) = 6 - 3 = 3.
Constraints:
1 <= nums.length <= 1040 <= nums[i] <= 1040 <= k <= 104
中文题目
给你一个整数数组 A,对于每个整数 A[i],可以选择 x = -K 或是 x = K (K 总是非负整数),并将 x 加到 A[i] 中。
在此过程之后,得到数组 B。
返回 B 的最大值和 B 的最小值之间可能存在的最小差值。
示例 1:
输入:A = [1], K = 0 输出:0 解释:B = [1]
示例 2:
输入:A = [0,10], K = 2 输出:6 解释:B = [2,8]
示例 3:
输入:A = [1,3,6], K = 3 输出:3 解释:B = [4,6,3]
提示:
1 <= A.length <= 100000 <= A[i] <= 100000 <= K <= 10000
通过代码
官方题解
方法 1:线性扫描
想法
如 最小差值 I 问题的解决方法,较小的 A[i] 将增加,较大的 A[i] 将变小。
算法
我们可以对上述想法形式化表述:如果 A[i] < A[j],我们不必考虑当 A[i] 增大时 A[j] 会减小。这是因为区间 (A[i] + K, A[j] - K) 是 (A[i] - K, A[j] + K) 的子集(这里,当 a > b 时 (a, b) 表示 (b, a) )。
这意味着对于 (up, down) 的选择一定不会差于 (down, up)。我们可以证明其中一个区间是另一个的子集,通过证明 A[i] + K 和 A[j] - K 是在 A[i] - K 和 A[j] + K 之间。
对于有序的 A,设 A[i] 是最大的需要增长的 i,那么 A[0] + K, A[i] + K, A[i+1] - K, A[A.length - 1] - K 就是计算结果的唯一值。
[]class Solution { public int smallestRangeII(int[] A, int K) { int N = A.length; Arrays.sort(A); int ans = A[N-1] - A[0]; for (int i = 0; i < A.length - 1; ++i) { int a = A[i], b = A[i+1]; int high = Math.max(A[N-1] - K, a + K); int low = Math.min(A[0] + K, b - K); ans = Math.min(ans, high - low); } return ans; } }
[]class Solution(object): def smallestRangeII(self, A, K): A.sort() mi, ma = A[0], A[-1] ans = ma - mi for i in xrange(len(A) - 1): a, b = A[i], A[i+1] ans = min(ans, max(ma-K, a+K) - min(mi+K, b-K)) return ans
复杂度分析
- 时间复杂度:$O(N \log N)$,其中 $N$ 是
A的长度。 - 空间复杂度:$O(1)$,额外空间就是自带排序算法的空间。
统计信息
| 通过次数 | 提交次数 | AC比率 |
|---|---|---|
| 6867 | 21403 | 32.1% |
提交历史
| 提交时间 | 提交结果 | 执行时间 | 内存消耗 | 语言 |
|---|