LeetCode-Smallest Range I

本文探讨了一种算法问题,即如何通过调整数组中的每个元素,使其最大值与最小值之间的差值达到最小。通过分析,我们了解到只需关注数组中的最大值和最小值,并通过特定的计算公式得出最小可能的差值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值