LeetCode周赛#103 Q1 Smallest Range I

题目来源:https://leetcode.com/contest/weekly-contest-103/problems/smallest-range-i/

问题描述

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. 1 <= A.length <= 10000
  2. 0 <= A[i] <= 10000
  3. 0 <= K <= 10000

------------------------------------------------------------

题意

给定数列A和一个正整数K,对于A的每一个元素,可以给它加上x,其中x∈[-K,K](每个元素加上的x可以不同),从而得到新数列B,问新数列B的最大值和最小值之差的最小值是多少?

------------------------------------------------------------

思路

由于每个元素加上的x值可以各不相同,因此考虑A数列最大值与最小值之差与x的上界K的关系,分类讨论即可。

------------------------------------------------------------

代码

class Solution {
public:
    const int inf = 0x3f3f3f;
    int smallestRangeI(vector<int>& A, int K) {
        int minv = inf, maxv = -inf, i, len = A.size();
        for (i=0; i<len; i++)
        {
            if (A[i] < minv)
            {
                minv = A[i];
            }
            if (A[i] > maxv)
            {
                maxv = A[i];
            }
        }
        int diff = minv + 2 * K - maxv;
        if (diff <= 0)
        {
            return -diff;
        }
        else
        {
            return 0;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/82827628