-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode1.txt
More file actions
48 lines (35 loc) · 990 Bytes
/
code1.txt
File metadata and controls
48 lines (35 loc) · 990 Bytes
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
Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].
If there is no solution possible, return -1.
Example :
A : [3 5 4 2]
Output : 2
for the pair (3, 4)
Code=>
public class Solution {
public static int maximumGap(final List<Integer> A) {
int maxDiff;
int i, j;
int n = A.size();
int RMax[] = new int[n];
int LMin[] = new int[n];
LMin[0] = A.get(0);
for (i = 1; i < n; ++i) {
LMin[i] = Math.min(A.get(i), LMin[i - 1]);
}
RMax[n - 1] = A.get(n - 1);
for (j = n - 2; j >= 0; --j) {
RMax[j] = Math.max(A.get(j), RMax[j + 1]);
}
i = 0; j = 0; maxDiff = 0;
while (j < n && i < n) {
if (LMin[i] <= RMax[j]) {
maxDiff = Math.max(maxDiff, j - i);
j++;
}
else {
i++;
}
}
return maxDiff;
}
}