import bisect


class Solution(object):
    def threeSumClosest(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: int
        """
        nums = sorted(nums)
        r_nums = nums[::-1]
        ready = []
        mi = +10 ** 10
        ma = -10 ** 10

        for a in nums:
            r_nums.pop(-1)
            for b in r_nums:
                c = target - a - b
                p = bisect.bisect_left(ready, c)
                if p < len(ready):
                    mi = min(mi, ready[p] - c)
                if p > 0:
                    ma = max(ma, ready[p - 1] - c)

            ready.append(a)

        if mi < -ma:
            return target + mi
        else:
            return target + ma
