Monday, February 8, 2021

[LeetCode] Heaters

Problem: 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.

Example:

Input: houses = [1,2,3], heaters = [2]
Output: 1
Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed.
Input: houses = [1,2,3,4], heaters = [1,4]
Output: 1
Explanation: The two heater was placed in the position 1 and 4. We need to use radius 1 standard, then all the houses can be warmed.
Input: houses = [1,5], heaters = [2]
Output: 3


Approach: Basically if we sort heaters array then we just need to find right position of every house in the sorted heaters array. Once we get that position what we can do is we can calculate the left and right distances and min of them will become a candidate for the radius. Ultimately we just need to return the maximum of all such candidates.

To get the right position of a house in heaters we can use binary search. 


Implementation in C#:

        public static int FindRadius(int[] houses, int[] heaters)

        {

            System.Array.Sort(heaters);

            int radius = 0;

            for (int i = 0; i < houses.Length; ++i)

            {

                // Documentation of Array.BinarySearch: https://docs.microsoft.com/en-us/dotnet/api/system.array.binarysearch?view=net-5.0

                int position = System.Array.BinarySearch(heaters, houses[i]);

                if (position >= 0)

                {

                    continue;

                }

                position = ~position;

                int leftDistance = position > 0 ? houses[i] - heaters[position - 1] : int.MaxValue;

                int rightDistance = position < heaters.Length ? heaters[position] - houses[i] : int.MaxValue;

                radius = Math.Max(radius, Math.Min(leftDistance, rightDistance));

            }

            return radius;

        }


Complexity: nlogm

No comments:

Post a Comment