An integer K
and a non-empty zero-indexed array A
consisting of N
integers are given.
A pair of integers (P, Q), such that 0 ≤ P ≤ Q < N
, is called a slice of array A.
A bounded_slice is a slice in which the difference between the maximum and minimum values in the slice is less than or equal to K. More precisely it is a slice, such that max(A[P], A[P + 1], ..., A[Q]) − min(A[P], A[P + 1], ..., A[Q]) ≤ K
.
The goal is to calculate the number of bounded_slices.
My solution is given below:
int solution(int K, int A[], int N){
// write your code in C90
int p, q, max, min, bndSlice = N;
for(p = 0; p < (N - 1); p++){
for(q = (p + 1); q < N; q++){
MaxMinSlice(A, p, q, &max, &min);
if((max - min) <= K){
bndSlice++;
}
if(bndSlice > 1000000000){
return 1000000000;
}
}
}
return bndSlice;
}
void MaxMinSlice(int A[], int p, int q, int *max, int *min){
int i;
*max = *min = A[p];
for(i = p; i <= q; i++){
if(*max < A[i]){
*max = A[i];
}
if(*min > A[i]){
*min = A[i];
}
}
}
How do I reduce the time complexity of the above code to O(N)?