LeetCode-Smallest Range I
阿新 • • 發佈:2018-12-11
Description: Given an array A of integers, for each integer A[i] we may choose any x with -K <= x <= K, and add x to A[i].
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 = 0 Output: 0 Explanation: B = [1]
Example 2:
Input: A = [0,10], K = 2
Output: 6
Explanation: B = [2,8]
Example 3:
Input: A = [1,3,6], K = 3
Output: 0
Explanation: B = [3,3,3] or B = [4,4,4]
Note:
- 1 <= A.length <= 10000
- 0 <= A[i] <= 10000
- 0 <= K <= 10000
題意:給定一個一維陣列A和一個整數K,現要求利用A和K得到陣列B,陣列B中的元素B[i] = A[i] + k(-K <= k <= K),使得返回的陣列B中元素最大值與最小值的差最小;
解法:我們現在關心的知識令陣列B中最大值與最小值的差最小,因此,對於A來說我們需要考慮的也僅僅是最大值max與最小值min(只有這兩個值會影響最終的結果);
- 如果max - min <= 2 * K,那麼說明我們可以利用K令A中的最小值和最大值相等
- 如果max - min > 2 * K,那麼我們只能利用K令A中的最小值與最大值儘量接近
Java
class Solution { public int smallestRangeI(int[] A, int K) { int min = A[0]; int max = A[0]; for (int x : A) { min = x < min ? x : min; max = x > max ? x : max; } return max - min <= 2 * K ? 0 : max - min - 2 * K; } }