-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
56 lines (42 loc) · 1.45 KB
/
Copy pathsolution.java
File metadata and controls
56 lines (42 loc) · 1.45 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
class Solution {
public ArrayList<Boolean> processQueries(int[] arr, int[][] queries) {
int n = arr.length;
// up[i] = farthest index reachable while remaining non-decreasing
int[] up = new int[n];
// down[i] = farthest index reachable while remaining non-increasing
int[] down = new int[n];
// Base case for the last element
up[n - 1] = n - 1;
// Build non-decreasing reach array
for (int i = n - 2; i >= 0; i--) {
if (arr[i] <= arr[i + 1])
up[i] = up[i + 1];
else
up[i] = i;
}
// Base case for the last element
down[n - 1] = n - 1;
// Build non-increasing reach array
for (int i = n - 2; i >= 0; i--) {
if (arr[i] >= arr[i + 1])
down[i] = down[i + 1];
else
down[i] = i;
}
ArrayList<Boolean> ans = new ArrayList<>();
// Process every query
for (int[] q : queries) {
int l = q[0];
int r = q[1];
// End of increasing part
int peak = up[l];
// If increasing part already reaches r
if (peak >= r)
ans.add(true);
// Otherwise decreasing part must cover the rest
else
ans.add(down[peak] >= r);
}
return ans;
}
}