[LeetCode] Heaters

475. Heaters

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int findRadius(vector<int>& houses, vector<int>& heaters) {
sort(heaters.begin(), heaters.end());
int res = 0;
for(auto house : houses) {
auto it = lower_bound(heaters.begin(), heaters.end(), house);
if(it == heaters.end())
res = max(res, abs(*prev(it) - house));
else if(it == heaters.begin())
res = max(res, abs(*it - house));
else
res = max(res, min(abs(*it - house), abs(*prev(it) - house)));
}

return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/02/27/PS/LeetCode/heaters/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.