-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
52 lines (48 loc) · 1.73 KB
/
Copy pathsolution.java
File metadata and controls
52 lines (48 loc) · 1.73 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
import java.util.PriorityQueue;
import java.util.Arrays;
import java.util.Comparator;
class Solution {
public boolean isPossible(int[] arr, int k) {
// Sort to be safe (GfG often provides sorted input, but it's safe to sort)
Arrays.sort(arr);
// PriorityQueue stores int[]{value, length}
PriorityQueue<int[]> pq = new PriorityQueue<>(new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if (a[0] == b[0])
return a[1] - b[1]; // smaller length first
return a[0] - b[0]; // smaller value first
}
});
int i = 0, n = arr.length;
while (i < n) {
if (pq.isEmpty()) {
pq.add(new int[] { arr[i], 1 });
i++;
} else {
int[] top = pq.peek();
if (arr[i] == top[0]) {
// same value -> start new subsequence
pq.add(new int[] { arr[i], 1 });
i++;
} else if (arr[i] == top[0] + 1) {
// extend shortest subsequence ending with top[0]
pq.poll();
pq.add(new int[] { arr[i], top[1] + 1 });
i++;
} else {
// arr[i] > top[0] + 1 -> top subsequence cannot be extended
if (top[1] < k)
return false;
pq.poll();
}
}
}
// check remaining subsequences
while (!pq.isEmpty()) {
if (pq.peek()[1] < k)
return false;
pq.poll();
}
return true;
}
}