leetcode 908. Smallest Range I

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数组的最大值和最小值,然后算差值,然后用+x去减少这个差值。明显答案就是看2K能不能覆盖这个差值呗

class Solution {
public:
    int smallestRangeI(vector<int>& A, int K) {
        int a = INT_MAX;
        int b = INT_MIN;
        for (int i = 0; i < A.size(); ++i) {
            a = min(a, A[i]);
            b = max(b, A[i]);
        }
        if (a == b) return 0;
        if (b - a <= 2*K) return 0;
        else {
            return b - a - 2*K;
        }
    }
};
posted on 2018-09-24 16:08  Beserious  阅读(142)  评论(0编辑  收藏  举报