Skip to content

Latest commit

 

History

History
36 lines (28 loc) · 1.36 KB

475.-heaters.md

File metadata and controls

36 lines (28 loc) · 1.36 KB

475. Heaters

  • Medium

  • Winter is coming! During the contest, your first job is to design a standard heater with a fixed warm radius to warm all the houses.

    Every house can be warmed, as long as the house is within the heater's warm radius range.

    Given the positions of houses and heaters on a horizontal line, return the minimum radius standard of heaters so that those heaters could cover all houses.

    Notice that all the heaters follow your radius standard, and the warm radius will the same.

Analysis

To solve this problem, we first add two imaginary heaters to both sides of the houses. With that, we made sure that every house is in between two heaters, and the maximum of the smaller distance of those is the answer.

class Solution(object):
    def findRadius(self, houses, heaters):
        """
        :type houses: List[int]
        :type heaters: List[int]
        :rtype: int
        """
        houses.sort()
        heaters.sort()
        heaters=[float('-inf')]+heaters+[float('inf')] # add 2 fake heaters
        ans,i = 0,0
        for house in houses:
            while house > heaters[i+1]:  # search to put house between heaters
                i +=1
            dis = min (house - heaters[i], heaters[i+1]- house)
            ans = max(ans, dis)
        return ans