-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInterval_Selection.cpp
More file actions
59 lines (45 loc) · 1.29 KB
/
Interval_Selection.cpp
File metadata and controls
59 lines (45 loc) · 1.29 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
// Problem: https://www.hackerrank.com/challenges/interval-selection/problem
// Approach: Greedy Technique - https://www.hackerrank.com/challenges/interval-selection/editorial
#include <bits/stdc++.h>
using namespace std;
// Sort the intervals based on their ending boundaries
bool compare(const pair <int, int> & p1, const pair <int, int> & p2)
{
return (p1.second < p2.second);
}
int main ()
{
ios::sync_with_stdio(false);
cin.tie(0);
int t, a, b, ans, n;
int last, limit;
cin >> t;
while(t--)
{
ans = 1;
last = limit = 0;
cin >> n;
vector < pair <int, int> > arr;
for (int i = 0; i < n ; i++) {
cin >> a >> b;
arr.push_back({a, b});
}
sort(arr.begin(), arr.end(), compare);
//After sorting, interval[0] will always be taken, so start loop variable from 1 (Note: ans is initialized to 1 already)
for (int i = 1; i < n; i++) {
if(arr[i].first > arr[last].second)
{
last = i;
ans++;
}
else if (arr[i].first > limit)
{
limit = arr[last].second;
last = i;
ans++;
}
}
cout << ans << "\n";
}
return 0;
}