Leetcode 1509. Minimum Difference Between Largest and Smallest Value in Three Moves

2021-08-06 15:28:14 浏览数 (1)

文章作者:Tyan 博客:noahsnail.com | CSDN | 简书

1. Description

2. Solution

**解析:**Version 1,先对数组进行排序,如果数字个数小于5个,则最小差一定为0,否则,由于至多修改三个数字,因此最小值的情况为修改前三个数字、修改后三个数字、前面修改一个后面修改两个、前面修改两个后面修改一个,枚举四种情况的值取最小即可。

  • Version 1
代码语言:javascript复制
class Solution:
    def minDifference(self, nums: List[int]) -> int:
        if len(nums) < 5:
            return 0
        nums.sort()
        return min(nums[-1] - nums[3], nums[-4] - nums[0], nums[-2] - nums[2], nums[-3] - nums[1])

Reference

  1. https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/

0 人点赞