Count the
number of array slices in an array of random integers such that the difference
between the min and the max values in the slice is <= k
public static
int getCountOfSlicesWithMinMaxDiffGEk(int[] A, int k){
int N = A.length;
int[] maxQ = new int[N+1];
int[] posmaxQ = new int[N+1];
int[] minQ = new int[N+1];
int[] posminQ = new int[N+1];
int firstMax = 0, lastMax = -1;
int firstMin = 0, lastMin = -1;
int j = 0, result = 0;
for (int i = 0; i < N; i++) {
while (j < N) {
while(lastMax >= firstMax
&& maxQ[lastMax] <= A[j]) {
lastMax -= 1;
}
lastMax += 1;
maxQ[lastMax] = A[j];
posmaxQ[lastMax] = j;
while (lastMin >= firstMin
&& minQ[lastMin] >= A[j]) {
lastMin -= 1;
}
lastMin += 1;
minQ[lastMin] = A[j];
posminQ[lastMin] = j;
if (maxQ[firstMax] -
minQ[firstMin] <= k) {
j += 1;
} else {
break;
}
}
System.out.println("result="+result
+ " i=" + i + " j="+ j);
result += (j-i);
if (result >= Integer.MAX_VALUE)
{
result = Integer.MAX_VALUE;
}
if (posminQ[firstMin] == i) {
firstMin += 1;
}
if (posmaxQ[firstMax] == i) {
firstMax += 1;
}
}
return result;
}
A: 3,5,7,6,3
K=2
result=0 i=0
j=2
result=2 i=1
j=4
result=5 i=2
j=4
result=7 i=3
j=4
result=8 i=4
j=5
9
No comments:
Post a Comment