Given an array n elements (n <= 10^5) Count the number of ranges [L; R] (L <= R) which has difference between the maximum and minimum is even.
For example, n = 5
a[] = {4, 5, 2, 6, 3}
The answer is 11: [1;1], [1;4], [1;5], [2;2], [2;4], [2;5], [3;3], [3;4], [3;5], [4;4], [5;5]
The time limit is 1 second
If n <= 1000, a natvie algorithm in O(n^2) will be ok. I think we can improve this approach by using stack or deque. But it's too hard.
Is there any effiecient approach?
One way to get
O(n log n)
can be to divide and conquer. Divide in the middle and add up the results for left and right. For the section with intervals that overlap the middle, we can use prefixes for max and min and calculate it inO(n)
. Remember to start the prefixes including both sides of the divide considered together. For the middle section spanning the example, we divide at 2 and haveThis example isn't great for the next step because there's no change. All together, the middle section of the divide and conquer method for the example, would account for
[1;4], [1;5], [2;4], [2;5], [3;4], [3;5]
.A more interesting middle:
We see that for each min, we want the counts extending until a lower min on the opposite side, paired with each of the maxes, first with the one it pairs with on the same side plus any lower or equal max on the opposite side, then the rest on the opposite side. We can get the latter in O(1) by storing prefix counts associated with odd maxes. It works because keeping in one direction, the max prefixes are monotonic so we just need the counts of how many of them are odd.
We perform the iteration in order of decreasing mins (or mirror an iteration on maxes). It doesn't matter which side we start on as long as only one side accounts for one min, and the iteration is sequential.
Next mins:
Last min: