Leetcode 946 Solution

This article provides solution to leetcode question 946 (smallest-range-ii)

https://leetcode.com/problems/smallest-range-ii

Solution

class Solution(object):
    def smallestRangeII(self, A, K):
        """
        :type A: List[int]
        :type K: int
        :rtype: int
        """
        if len(A) <= 1:
            return 0

        A.sort()

        ans = A[-1] - A[0]
        for i in range(len(A) - 1):
            ans = min(ans, max(A[-1] - K, A[i] + K) - min(A[0] + K, A[i + 1] - K))

        return ans