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

2022/2/5 20:15:17

本文主要是介绍Leetcode 1509. Minimum Difference Between Largest and Smallest Value in Three Moves [Python],对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

可处理三次,那么能处理的其实是“丢掉”3个最小的数字或者3个最大的数字,或者6个数字里选3个(最小,次小,最大)(最小,次大,最大),所以也就是要在这4种subarray中选出最大最小值差最小的那个。
先sort,选出上述4种newnums。计算差值,找最小。

class Solution:
    def minDifference(self, nums: List[int]) -> int:
        if len(nums) <= 4:return 0
        nums.sort()
        newnum1 = nums[:-3]
        newnum2 = nums[1:-2]
        newnum3 = nums[2:-1]
        newnum4 = nums[3:]
        arr = [ newnum1, newnum2, newnum3, newnum4]
        res = float('inf')
        for thenums in arr:
            res = min(res, max(thenums) - min(thenums))
        return res


这篇关于Leetcode 1509. Minimum Difference Between Largest and Smallest Value in Three Moves [Python]的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程