-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMax Distance.java
More file actions
60 lines (39 loc) · 1.3 KB
/
Max Distance.java
File metadata and controls
60 lines (39 loc) · 1.3 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
60
public class Solution {
// DO NOT MODIFY THE LIST. IT IS READ ONLY
public class Type{
int data;
int prev;
public Type(int data, int prev){
this.data = data;
this.prev = prev;
}
}
public int maximumGap(final List<Integer> A) {
int N = A.size();
ArrayList<Type> B = new ArrayList<Type>();
for(int i = 0; i < N; i++)
B.add(new Type(A.get(i), i));
Collections.sort(B, new Comparator<Type>(){
public int compare(Type a, Type b){
return a.data - b.data;
}
});
int[] preFix = new int[N];
int max = 0;
for(int i = N - 2; i >= 0; i--){
if(B.get(i+1).prev > max)
max = B.get(i+1).prev;
preFix[i] = max;
}
int ans = 0;
for(int idx = 0; idx < N; idx++){
int i = B.get(idx).prev;
int j = preFix[idx];
if(j < i)
continue;
if(j - i > ans)
ans = j - i;
}
return ans;
}
}