Repository navigation
Expand file tree
/
Copy pathHeaters_BinarySearch.cpp
More file actions
63 lines (53 loc) · 1.66 KB
/
Copy pathHeaters_BinarySearch.cpp
File metadata and controls
63 lines (53 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Solution
{
public:
// Check if current radius can heat all houses
bool canAllHousesBeHeated(vector<int> &heaters, vector<int> &houses, int radius)
{
int houseIdx = 0;
for (int heater : heaters)
{
while (houseIdx < houses.size() &&
houses[houseIdx] >= heater - radius &&
houses[houseIdx] <= heater + radius)
{
houseIdx++;
}
// early exit
if(houseIdx == houses.size())
return true;
}
return houseIdx == houses.size(); // All houses covered
}
int findRadius(vector<int> &houses, vector<int> &heaters)
{
sort(houses.begin(), houses.end());
sort(heaters.begin(), heaters.end());
int left = 0, right = 1e9;
int answer = -1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (canAllHousesBeHeated(heaters, houses, mid))
{
answer = mid; // Mid works, try smaller radius
right = mid - 1;
}
else
{
left = mid + 1; // Mid too small, increase radius
}
}
return answer;
}
};
/*
Approach:
- Each heater can heat houses in the range [heater - radius, heater + radius]
- Binary search on the minimum required radius in range [0, 1e9]
- For each mid (radius), check if all houses are covered using a two-pointer scan
- If mid works → store as possible answer and search left
- If not → increase radius
Time: O((H + N) log(1e9)), where H = #houses, N = #heaters
Space: O(1)
*/