forked from imnishant/GeeksforGeeks-Java-Solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGreedy Algorithm
80 lines (68 loc) · 1.53 KB
/
Greedy Algorithm
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// { Driver Code Starts
import java.util.*;
import java.lang.*;
class Pair
{
int x;
int y;
public Pair(int a, int b)
{
x = a;
y = b;
}
}
class Chainlength
{
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
int n = sc.nextInt();
Pair pr[] = new Pair[n];
int arr[] = new int[2*n];
for(int i = 0; i < 2*n; i++)
{
arr[i] = sc.nextInt();
}
for(int i = 0, j = 0; i < 2*n-1 && j < n; i = i+2, j++)
{
pr[j] = new Pair(arr[i], arr[i+1]);
}
GfG g = new GfG();
System.out.println(g.maxChainLength(pr, n));
}
}
}
// } Driver Code Ends
/*class CompareByFirst implements Comparator<Pair>
{
public int compare(Pair a, Pair b)
{
return a.x - b.x;
}
}*/
class GfG
{
int maxChainLength(Pair arr[], int n)
{
Comparator<Pair> comp = new Comparator<Pair>(){
public int compare(Pair a, Pair b)
{
return a.y - b.y;
}
};
Arrays.sort(arr, comp);
int count = 1;
Pair selected = arr[0];
for(int i=1 ; i<n ; i++)
{
if(selected.y < arr[i].x)
{
selected = arr[i];
count++;
}
}
return count;
}
}