Given two arrays a
and b
of length n
. I need to find amount of pairs (l, r), 1 <= l <= r <= n
such that max(a[l], ..., a[r]) = min(b[l], ..., b[r])
.
I have this code:
int answer = 0;
for (int i = 0; i < n - 1; i++) {
int l = i;
int r = l;
while (r < n) {
int a_t = query(A, l, r, false); \ max on the segment
int b_t = query(B, l, r, true); \ min on the segment
if (a_t == b_t) {
answer++;
r++;
} else if (a_t > b_t) {
break;
} else {
r++;
}
}
}
It works for O(n^2), but is there a way to optimize it?