[LeetCode] Minimum Rectangles to Cover Points

3111. Minimum Rectangles to Cover Points

You are given a 2D integer array points, where points[i] = [xi, yi]. You are also given an integer w. Your task is to cover all the given points with rectangles.

Each rectangle has its lower end at some point (x1, 0) and its upper end at some point (x2, y2), where x1 <= x2, y2 >= 0, and the condition x2 - x1 <= w must be satisfied for each rectangle.

A point is considered covered by a rectangle if it lies within or on the boundary of the rectangle.

Return an integer denoting the minimum number of rectangles needed so that each point is covered by at least one rectangle.

Note: A point may be covered by more than one rectangle.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int minRectanglesToCoverPoints(vector<vector<int>>& points, int w) {
vector<int> A;
for(int i = 0; i < points.size(); i++) A.push_back(points[i][0]);
sort(rbegin(A), rend(A));
int res = 0;
while(A.size()) {
int until = A.back() + w;
while(A.size() and A.back() <= until) A.pop_back();
res++;
}
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2024/04/13/PS/LeetCode/minimum-rectangles-to-cover-points/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.