Leetcode 475 Solution

This article provides solution to leetcode question 475 (heaters)

https://leetcode.com/problems/heaters

Solution

class Solution {
public:
    int findMinimumDistance(vector<int>& a, int target)
    {
        int l = 0;
        int r = a.size() - 1;

        while (l <= r)
        {
            int m = (l + r) / 2;

            if (a[m] >= target)
                r = m - 1;
            else
                l = m + 1;
        }

        int distance = INT_MAX;

        if (r != -1)
            distance = min(distance, abs(a[r] - target));

        if (l != a.size())
            distance = min(distance, abs(a[l] - target));

        return distance;
    }

    int findRadius(vector<int>& houses, vector<int>& heaters) {
        sort(heaters.begin(), heaters.end());

        int min_radius = 0;
        for (int i = 0; i < houses.size(); i++)
        {
            min_radius = max(min_radius, findMinimumDistance(heaters, houses[i]));
        }

        return min_radius;
    }
};