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

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

class Solution:
    def minDifference(self, nums: List[int]) -> int:
        n=len(nums)
        if(n<=3):
            return 0
        nums.sort()
        k=n-3
        # Fixed size sliding window of size k
        # See https://leetcode.com/problems/minimum-difference-between-largest-and-smallest-value-in-three-moves/discuss/730567/JavaC%2B%2BPython-Straight-Forward if you don't understand
        i=0
        j=0
        ans=float('inf')
        while(j<n):
            
            if(j-i+1<k):
                j+=1
            elif(j-i+1==k):
                ans=min(ans,nums[j]-nums[i])
                i+=1
                j+=1
        return ans

Last updated