Heaters Problem


Description

LeetCode Problem 475.

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 heatersso that those heaters could cover all houses.

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

Example 1:

1
2
3
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.

Example 2:

1
2
3
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.

Example 3:

1
2
Input: houses = [1,5], heaters = [2]
Output: 3

Constraints:

  • 1 <= houses.length, heaters.length <= 3 * 10^4
  • 1 <= houses[i], heaters[i] <= 10^9


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
    int findRadius(vector<int>& houses, vector<int>& heaters) {
        if (heaters.size() == 0) {
            return 0;
        }
        sort(houses.begin(), houses.end());
        sort(heaters.begin(), heaters.end());
        int radius = 0;
        int index = 0;
        for (int i = 0; i < houses.size(); i++) {
            while (index + 1 < heaters.size() && (abs(heaters[index+1] - houses[i]) <= abs(heaters[index] - houses[i]))) {
                index++;
            }
            radius = max(radius, abs(heaters[index] - houses[i]));
        }
        return radius;
    }
};




Related Posts

Find K Closest Elements Problem

LeetCode 658. Given a sorted integer array arr, two integers...

Count Binary Substrings Problem

LeetCode 696. Give a binary string s, return the number...

String Compression Problem

LeetCode 443. Given an array of characters chars, compress it...

Shortest Unsorted Continuous Subarray Problem

LeetCode 581. Given an integer array nums, you need to...

Reverse Words In A String III Problem

LeetCode 557. Given a string s, reverse the order of...

Reverse String II Problem

LeetCode 541. Given a string s and an integer k,...