三步中最大和最小值之间的最小差异

WBOY
发布: 2024-07-18 22:44:21
原创
1199 人浏览过

Minimum Difference Between Largest and Smallest Value in Three Moves

1509。三步中最大和最小值之间的最小差异

给你一个整数数组 nums。

一步即可选择 nums 的一个元素,并将其更改为任意值

返回nums的最大和最小值之间的最小差值执行最多三步后.

示例1:

  • 输入: nums = [5,3,2,4]
  • 输出: 0
  • 说明:我们最多可以进行 3 步。
  In the first move, change 2 to 3. nums becomes [5,3,3,4].
  In the second move, change 4 to 3. nums becomes [5,3,3,3].
  In the third move, change 5 to 3. nums becomes [3,3,3,3].
  After performing 3 moves, the difference between the minimum and maximum is 3 - 3 = 0.
登录后复制

示例2:

  • 输入: nums = [1,5,0,10,14]
  • 输出: 1
  • 说明:我们最多可以进行 3 步。
  In the first move, change 5 to 0. nums becomes [1,0,0,10,14].
  In the second move, change 10 to 0. nums becomes [1,0,0,0,14].
  In the third move, change 14 to 1. nums becomes [1,0,0,0,1].
  After performing 3 moves, the difference between the minimum and maximum is 1 - 0 = 1.
  It can be shown that there is no way to make the difference 0 in 3 moves.
登录后复制

示例 3:

  • 输入: nums = [3,100,20]
  • 输出: 0
  • 说明:我们最多可以进行 3 步。
  In the first move, change 100 to 7. nums becomes [3,7,20].
  In the second move, change 20 to 7. nums becomes [3,7,7].
  In the third move, change 3 to 7. nums becomes [7,7,7].
  After performing 3 moves, the difference between the minimum and maximum is 7 - 7 = 0.
登录后复制

约束:

  • 1 5
  • -109 9

解决方案:

class Solution {

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function minDifference($nums) {
        $n = count($nums);

        // If the array has 4 or fewer elements, the difference is zero because we can remove all but one element.
        if ($n <= 4) {
            return 0;
        }

        // Sort the array to facilitate the calculation of differences after removals.
        sort($nums);

        // We consider removing 0, 1, 2, or 3 elements from the start or the end.
        // Calculate the differences:
        // 1. Remove 3 from start: nums[n-1] - nums[3]
        // 2. Remove 2 from start, 1 from end: nums[n-2] - nums[2]
        // 3. Remove 1 from start, 2 from end: nums[n-3] - nums[1]
        // 4. Remove 3 from end: nums[n-4] - nums[0]
        $differences = [
            $nums[$n - 1] - $nums[3],
            $nums[$n - 2] - $nums[2],
            $nums[$n - 3] - $nums[1],
            $nums[$n - 4] - $nums[0]
        ];

        // Return the minimum difference.
        return min($differences);
    }
}
登录后复制

联系链接

  • 领英
  • GitHub

以上是三步中最大和最小值之间的最小差异的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板