We need to read problem: given n and k, and array h[1..n] (heights of books). We need to find maximum number of books (maximum length of a subarray) such that max - min <= k. That's typical sliding window problem for maximum window length with condition. But also we need to count all intervals (contiguous subarrays) of that maximum length that satisfy the condition? Actually reading problem statement: "In the first line ... where a is the maximum amount of books the organizers can include into the exposition, and b — the amount of the time periods, during which Berlbury published a books, and the height difference between the lowest and the highest among these books is not more than k millimeters."
Interpretation: They want to find the maximum possible number a such that there exists at least one contiguous segment of length a with max-min <= k. Then output a and the number b of such segments (i.e., all contiguous subarrays of length exactly a that satisfy the condition). Then output each such segment's start and end indexes (1-indexed). However, careful: "the amount of the time periods, during which Berlbury published a books" means periods where the number of books is a? Could also be periods with at least a books? But the phrasing: "during which Berlbury published a books" suggests exactly a books. Usually in such problems (like "Maximum Subarray with condition" we find maximum length, then output all intervals achieving that length. So I think that's correct.
But let's verify examples:
Example 1:
n=3, k=3
h=[14,12,10]
We can find all subarrays where max-min <=3:
- [14] diff=0 (<=3) length1
- [12] length1
- [10] length1
- [14,12] diff=2 length2
- [12,10] diff=2 length2
- [14,12,10] diff=4 >3 length3 invalid.
Maximum length a=2. Count of subarrays of length2 that satisfy: there are two: (1,2) and (2,3). So output matches.
Example 2:
n=2, k=0
h=[10,10]
All subarrays:
- [10] len1 diff0
- [10] len1 diff0
- [10,10] len2 diff0
Maximum length a=2. Subarrays of length2 that satisfy: only (1,2) so b=1. Output matches.
Example 3:
n=4, k=5
h=[8,19,10,13]
Check subarrays:
- length1: all okay.
- length2: (1,2): 8,19 diff=11>5; (2,3):19,10 diff=9>5; (3,4):10,13 diff=3<=5 => valid; others? (1,2) invalid, (2,3) invalid, (3,4) valid. Also (1,2) etc.
- length3: (1,3):8,19,10 diff=11>5; (2,4):19,10,13 diff=9>5 -> invalid.
- length4: diff=11>5.
So maximum length a=2. Subarrays of length2 that satisfy: only (3,4) (indexes 3 and 4). So b=1. Output: "2 1" and "3 4". That matches.
Thus, indeed, we need to find the maximum possible length L such that there exists at least one subarray of length L with max-min <= k. Then output the count and list of all such subarrays of length L.
We need to solve for n up to 1e5, h_i up to 1e6, k up to 1e6.
We can do sliding window to compute maximum window length. But sliding window typically finds the longest subarray ending at each position? Actually we can use two-pointer technique: maintain window [l, r] such that condition holds, expand r, if condition fails, increment l until holds. Keep track of max window length encountered. But that only gives us length, not list of all intervals achieving that max length. However we can adapt: after we know the max length L, we can scan for all starting indices i such that subarray [i, i+L-1] satisfies condition. Because L is up to n, scanning each subarray and checking condition naively O(nL) is too slow. But we can precompute data structures to answer queries quickly? Or we can use sliding window again to record all windows of max length while we compute? Actually we can run the two-pointer algorithm once, and while we slide, when we achieve a window of length L, we can record its boundaries. But note that the maximum length L might be discovered multiple times during the sliding. However we need to ensure we capture all windows of exactly length L that satisfy condition.
Option: Use two-pointer to maintain a window that satisfies condition at each step (as we move r from 1 to n). For each r, we adjust l to smallest index such that condition holds. The current window length is len = r-l+1. If len > current max, we update max and clear list of intervals, then add (l, r) if len==max? But careful: There might be windows that are not minimal left for given right but still have max length. For a fixed right r, the maximal window satisfying condition might have l as the smallest possible such that condition holds, but there might be other left values > l that also satisfy condition and yield the same length? Actually for a given r, if the smallest l yields len, then any larger left would give smaller len, so the maximum length for that r is this len. So sliding window with minimal l gives the longest window ending at r. As we vary r, we capture each possible maximum window ending at each r. But could there exist a window of length L that is not the longest for its ending r? Suppose for some r, the longest window ending at r has length > L, but there is also a window ending at r of length L that also satisfies condition? That would be a subwindow inside the longer window. Since condition is monotonic? Actually if a window satisfies max-min <= k, any subwindow also satisfies? Not necessarily: subwindow might have larger difference? Wait: If the larger window's max-min <= k, then any subwindow's max-min is also <= that max-min, so also <= k. So if we have a window [l, r] that satisfies condition, then any subwindow inside it also satisfies. Therefore if we have a window ending at r with length Lmax (largest), then any shorter length also works. So there will be windows of length L (if L <= Lmax) ending at r as well, by shifting left to appropriate position. So if we only record the longest window for each r, we might miss some windows of length L that are not the longest for that r, but they are essentially subwindows of the longest windows. But we only care about the maximum possible length Lmax. So we need to capture all windows of length exactly Lmax. Are all windows of length Lmax necessarily the longest windows for their ending r? For a window [i, j] of length Lmax, it is the longest window ending at j only if no longer window ending at j exists. But since it's length Lmax, which is the maximum length overall, no window ending at j can be longer than Lmax (since max overall is Lmax). So any window of length Lmax ending at j is the longest for that j (or ties). However there could be multiple windows of length Lmax ending at same j? For fixed j, if [i1, j] and [i2, j] both have length Lmax, then i1 = i2 = j-Lmax+1 because length is fixed. So only one left for each right. So each window of maximum length corresponds uniquely to its right endpoint r = i+L-1. So we can capture each such window by its right endpoint when we process r, if we can detect that the longest window ending at r has length Lmax.
Therefore algorithm:
- Use two pointers l=0 (0-index) or 1-index. We'll maintain multiset or data structures to get min and max in window quickly. For sliding window, we can use two deques for monotonic (min and max) to get O(1) amortized. Or use a balanced BST but we need efficient.
We need to compute for each r (from 1 to n) the smallest l such that condition holds (max-min <= k). We'll maintain two deques: one for max (decreasing), one for min (increasing). As we add h[r], we update deques. While current window's max - min > k, we increment l and remove element at l from deques (if the element is at front of deques). Then we have valid window [l, r] with minimal l. The length = r-l+1. If length > current maximum, update max_len = length, clear list intervals, and push (l, r) if length == max_len? Actually when length > max_len, we set max_len = length and then we need to add this interval? Since length > previous max_len, we want only intervals of new max_len, so we clear and add (l, r). But careful: Could there be other intervals of same length we haven't seen? As we iterate, if later we get length == max_len, we add them. However what about intervals of the same length that are not the minimal left for some r? As argued, each maximum length interval has unique right endpoint, and when we process that r, the minimal l that makes condition hold will be the left endpoint of that maximal interval? Not necessarily: Consider window of length Lmax. Is it guaranteed that the minimal l for that r yields exactly that window? Suppose we have array where for right index j, the longest valid window is of length Lmax, but there could be also a valid window [l', j] with l' > minimal l but same length Lmax? That would mean minimal l = l'? Because if both windows have same length, they would have same left index because length = j - left + 1, so left = j - Lmax + 1. So the left is uniquely determined by j and length. So if there is a window of length Lmax ending at j, then the left must be j - Lmax + 1. The minimal l for that j must be <= that left. If it's strictly less, then the window [l_min, j] is longer than Lmax, which contradicts that Lmax is the overall maximum. Therefore for that j, the minimal l must be exactly j - Lmax + 1. So indeed, when we process r = j, the minimal l will be the left of the max-length window. So we can capture all max-length intervals by checking, each time after adjusting l to satisfy condition, if (r-l+1) == max_len (which is currently the global maximum), then we add (l, r) to a list.
But we need to be careful about order: We maintain current max_len. When we update max_len to a larger value, we also want to add the current interval as it's the first of that new max length. So we should add interval whenever length == max_len. However if later we update max_len to a larger value, we clear list and start over.
Thus, a single pass with sliding window can compute max_len and list of intervals (l, r) achieving that length.
We must output intervals in the order they appear? The problem doesn't specify order. But examples show in increasing order of start index. Since we process r increasing, adding intervals as we see them, they will be naturally sorted by end index, which corresponds to increasing start index as well because length is constant. So we can output them in the order we collected.
Complexity O(n). Use 0-index or 1-index? We'll use 0-index arrays, but output indexes from 1 to n inclusive.
Implementation details:
- n, k read.
- vector h(n)
- deque maxdq, mindq (store indices)
- l = 0
- max_len = 0
- vector<pair<int,int>> res (list of intervals)
- for r from 0 to n-1:
- while !maxdq.empty() and h[maxdq.back()] <= h[r] (for decreasing), pop back. Then push r.
- while !mindq.empty() and h[mindq.back()] >= h[r] (for increasing), pop back. Then push r.
- Now check condition: while (h[maxdq.front()] - h[mindq.front()] > k):
// need to move l forward, removing elements that are out of window.
if (maxdq.front() == l) maxdq.pop_front();
if (mindq.front() == l) mindq.pop_front();
l++;
- length = r - l + 1
- if (length > max_len):
max_len = length;
res.clear();
res.push_back({l, r});
- else if (length == max_len):
res.push_back({l, r});
But is it correct? Let's test on examples.
Example1: n=3, k=3, h=[14,12,10]
Initialize l=0,max_len=0,res empty.
r=0: add index0 to deques.
maxdq: [0], mindq:[0], condition h[0]-h[0]=0<=3. So length=1 > max_len(0): update max_len=1, clear res, add (0,0)
r=1: add index1: for maxdq: while back <=12? front is 0(14) >12? Actually we need decreasing: while back val <= h[r] pop. At back is index0 with 14, 14 <=12? false, so keep. Push 1 -> maxdq [0,1]. mindq: while back val >= h[r] (10? Wait h[1]=12) Actually mindq: back index0 has 14, 14 >=12? true, so pop back. mindq becomes empty, push 1 -> [1]. Condition: max front 0 (14), min front 1 (12), diff=2 <=3. length=2 >1? yes (l still 0). So update max_len=2, clear res, add (0,1).
r=2: add index2 (10). maxdq: while back <=10? back is index1(12) >10? 12<=10 false, keep. push 2 -> [0,1,2]. mindq: while back >=10? back index1(12) >=10 true pop back; now back? maybe empty? Actually after popping, mindq currently [1]? Wait we need to check: before adding, mindq had [1] (index1=12). Then while back val >= h[2] (10) -> 12>=10 true, pop back, now empty. Then push 2 -> mindq [2]. Condition: max front = index0 (14), min front = index2 (10) diff=4 > k=3. So while loop:
if maxdq.front() == l (0) then pop; same for mindq: front=2 not equal l? Actually mindq front =2 !=0, so only maxdq.pop_front() -> maxdq becomes [1,2] (front 1). l++ -> l=1.
Now condition: max front index1 (12), min front index2 (10) diff=2 <=3. length = 2-1+1 =2. Now length == max_len (2) -> so add (1,2) to res. But note we also had res cleared earlier and only added (0,1). But now we add (1,2) to res, so res contains (0,1) and (1,2). However the correct answer should be only intervals of maximum length? maximum length is 2, intervals are (1,2) and (2,3)? Actually using 1-index: (1,2) and (2,3). That corresponds to (0,1) and (1,2) in 0-index. Good. So we have both.
But we need to check if (0,1) is indeed valid at this point? At r=1 we added (0,1). At r=2 after shrinking, we got (1,2). So res now contains both. That matches expected.
Now after loop, we output max_len=2 and b=2, and intervals (1,2) and (2,3) in 1-index.
Works.
Example2: n=2,k=0,h=[10,10]
r=0: length=1 >0 => update max_len=1, add (0,0)
r=1: add index1; maxdq: back 0 (10) <=10? Since 10 <=10, we pop back (if condition is <=, we pop equal to maintain decreasing? For max we want strictly decreasing? Actually we need to ensure that when elements equal, we may pop or not? In typical implementation for sliding window max, we pop while back <= new element, so that we keep decreasing but allow duplicates? If we pop <=, then for equal values we pop the earlier one, so the deque will contain indices with strictly decreasing values? That might cause issues for condition because if there are equal values, we want to know the max/min correctly. But as long as we maintain that the front is the max within window, popping equal values can be acceptable if we pop earlier ones, but then when we later remove from front, we need to ensure we have correct count. For max, if values equal, popping earlier ones doesn't lose info because the later one will be in deque and will be considered max, and when the earlier one leaves window, we don't need to remove it because it's already gone. However if we pop earlier equal values, then later when we need to pop from front if it's out of window, it's fine because the front may be a later index. But we must be careful: If we pop the earlier equal, the later one will stay. That's fine because the max is same. For min, we pop while back >= new element, similarly.
Now r=1: maxdq: before push, we have [0] (10). Since h[1]=10, while back <=10 (condition for max), 10 <=10 true, so pop back (remove 0). Then push 1 -> maxdq [1]. mindq: previously [0] (10). while back >=10: 10>=10 true, pop back, then push 1 -> mindq [1]. Condition: max front=1 (10), min front=1 (10) diff=0 <=0. length = r-l+1, l is still 0? l=0, length=2 > max_len=1 => update max_len=2, clear res, add (0,1). So after loop res has (0,1) only. Output: max_len=2, b=1, interval (1,2). Good.
Example3: n=4,k=5,h=[8,19,10,13]
r=0: length1, update max_len=1, add (0,0)
r=1: add index1 (19). maxdq: [0] then while back <=19? 8<=19 pop back (0), push1 -> [1]. mindq: [0] while back >=19? 8>=19 false, push1 -> [0,1]? Actually for mindq we need increasing: we pop while back >= new element? Typically for min deque we maintain increasing order, so we pop while back >= new element to keep increasing. But careful: If we want min, we want front to be smallest. So we maintain non-decreasing order. So when we have [0] (8) and new element 19, condition back >= 19? 8>=19 false, so push1 -> [0,1]. Condition: max front=1 (19), min front=0 (8) diff=11 >5. So while loop:
if maxdq.front() == l (0)? max front=1 !=0, so not. mindq.front()==0? yes, front=0 (8) == l, so pop_front mindq -> becomes [1]. l++ -> l=1.
Now check: window [1,1] (only index1). max front=1, min front=1 (since mindq now [1]? after pop, mindq front =1), diff=0 <=5. length = 1-1+1=1. Not > max_len (1). So no update. res still (0,0) from earlier? But we cleared when we updated? At r=1, we earlier didn't update because length was 1? Actually at start of loop, we added index1, we did not yet check condition before while. After adjusting, length=1, not > max_len(1). So max_len remains 1. So we don't add (1,1) because length==max_len? It is equal to max_len (1) but we need to decide if we should add intervals of length max_len when they appear? In our algorithm we add if length == max_len after adjustment. That would cause us to add (1,1) as well, which is a max-length interval (length 1). But we are only interested in the final maximum length, which may be 2. So if we add all intervals with length equal to current max_len during processing, we might collect many length-1 intervals before we discover max_len=2. But later when we update max_len to 2, we clear the list and start over. So that's fine: we will discard length-1 intervals when we first get a length 2. In this case, we had (0,0) as res. At r=1 after adjusting, length=1, and we check if length == max_len (1) then we would push (1,1) if we have that logic. In our described algorithm earlier we said: after while loop, if length > max_len update, else if length == max_len push. So at r=1, length=1 == max_len (1), so we would push (1,1) to res. But then res contains (0,0) and (1,1). That's okay because later when we find length 2, we clear res and only keep the length 2 intervals. So we need to ensure that when we update max_len to a larger value, we clear res. So that's fine.
Now r=2: add index2 (10). Update deques.
- maxdq currently [1] (19). For max, while back <=10? 19<=10 false, push2 -> [1,2].
- mindq currently after previous steps: we had mindq [1] after popping front earlier? Actually after r=1, mindq became [1]? Let's recalc: after adjusting at r=1, we popped mindq front (0) because l was 0 and we incremented l to 1. Then after that, mindq front maybe 1? Yes mindq was [1] (since we added index1 earlier). So mindq now [1] (19). For min, we want increasing order, so while back >=10? back is index1=19, 19>=10 true, pop back. Now mindq empty. Push2 -> [2] (10).
Now condition: max front = index1 (19), min front = index2 (10), diff=9 >5. So while loop:
if maxdq.front() == l? l=1 currently, max front=1? yes it's 1. So pop max front => maxdq becomes [2] (front 2).
if mindq.front() == l? mindq front=2, l=1, no.
l++ -> l=2.
Now check condition: window [2,2] only index2. max front=2 (10), min front=2 (10), diff=0 <=5. length=1. Not > max_len (1). So length==max_len? yes, add (2,2) to res? But we already have res containing length-1 intervals. So res now includes (0,0), (1,1), (2,2). That's okay.
r=3: add index3 (13). Update deques.
- maxdq currently [2] (10). while back <=13? 10<=13 true, pop back (2), now empty, push3 -> [3] (13).
- mindq currently [2] (10). while back >=13? 10>=13 false, push3 -> [2,3] (since increasing order, 10 then 13).
Now condition: max front=3 (13), min front=2 (10), diff=3 <=5. So window [l=2, r=3] is valid. length = 2. Compare with max_len=1: length > max_len, so update max_len=2, clear res, add (2,3) to res.
Then after that, length == max_len? Already handled in > branch? We should only add in else if length == max_len after maybe updating. So (2,3) added.
Now loop ends. res contains only (2,3). Output max_len=2 and interval (3,4) in 1-index. Good.
Thus algorithm works.
Now we need to ensure the sliding window with deques works correctly for condition. However the condition is max - min <= k. We maintain deques for max and min. The while condition to shrink l: while (h[maxdq.front()] - h[mindq.front()] > k) { ... }.
But note: The deques may have front indices that are out of current window? Actually we always remove from front when the index equals l while shrinking. But during the while loop, we only remove front when it equals l. This ensures that front indices are within window [l, r] because we only increment l and remove front if they are exactly l. However before we start the while loop, we have added new element at r, and l hasn't changed. The window currently [l, r] might have max and min coming from deques that contain indices from l to r. But after adding r, some indices may have been removed from deques due to pops from back, but all indices in deques are within [l, r] because we never removed indices that are < l from front yet. However l may still be such that window is invalid. When we shrink, we increase l, and we remove front if they match l, so after that deques have indices >= new l. So the condition check uses front values that are guaranteed to be within [l, r] after removal. So it's correct.
Edge Cases: k >= 0. n=1.
Also, need to consider duplicate values. In deques, we need to correctly handle equal elements. Our popping strategy: for max, while (!maxdq.empty() && h[maxdq.back()] <= h[r]) maxdq.pop_back(); then push r. For min, while (!mindq.empty() && h[mindq.back()] >= h[r]) mindq.pop_back(); then push r. This removes older equal elements and keeps the newer one. That's fine because we want to keep the index that is more recent, so when we later shrink, if the front is the newest index, it's fine.
But is there any scenario where removing equal values could cause us to lose track of the correct max/min after some elements are removed? Let's test: Suppose window has values: [5,5] with k=0. At r=0: maxdq [0], mindq [0]. At r=1: For max: back=0, h[0]=5 <= h[1]=5 true, pop back, then push 1 => maxdq [1]. For min: back=0, h[0]=5 >=5 true, pop back, push1 => mindq [1]. Condition: max-min=0. Good.
Now if we shrink l: l was 0, then we increment to 1. Check if maxdq.front() == l? front=1, l=0? no. But we need to remove element 0 from deques. But element 0 is already gone from both deques because we popped it when adding r=1. So no need to remove. So it's fine.
Now consider scenario where we have equal values but we need to keep older index because newer is outside window? Actually when we pop equal values from back, we remove older indices. So the deque will contain the newest index for that value. That is good because older indices will leave window earlier. So it's okay.
Thus sliding window with deques works.
But we need to also consider that we need to output all intervals of maximum length. However note: There could be intervals that have length = max_len but are not discovered as minimal left for a given right? As argued, each such interval corresponds to a right endpoint j. At step r=j, after adjusting l to minimal left, if the window length equals max_len, then l must equal j-max_len+1. So we will capture it. So it's fine.
One nuance: Suppose we have a scenario where the maximum length L is discovered at some r, but later after further processing, we may discover that same length L occurs again for some r but the window might have l minimal that yields length exactly L, but perhaps there is also another interval of same length L that ends at some r, but the minimal l for that r is less than j-L+1? That cannot happen because if minimal l is less than that, then length > L, contradicting L is max. But could it be that minimal l is greater than j-L+1? That would mean the window of length L starting at j-L+1 does not satisfy condition (since minimal l is greater). So then that interval is invalid. So no.
Thus algorithm should collect all valid intervals of maximum length.
Now we must output the intervals in order? The problem examples show increasing start indices. Our algorithm processes r increasing, so intervals will be added in order of increasing end index (and thus start index because length fixed). So that's fine.
But careful: If there are multiple intervals of same maximum length, they may overlap? That's okay.
Now complexity: O(n). Memory O(n) for deques.
Implementation details: Use 0-index. Output intervals as l+1 and r+1.
Edge Cases: n=0? n>=1. k could be large such that all books can be included. Then max_len = n, and we need to count intervals of length n? Only one interval (1,n) if the whole array satisfies condition. But wait: Could there be multiple intervals of length n? Only one because only whole array length n. So b=1. That works.
But what if condition holds for whole array and also for other windows of length n? Only possible if n is length, there is only one contiguous segment of length n (the whole array). So b=1. So correct.
Also, what if k is such that there are many windows of length L? e.g., constant array: all h same. Then condition always holds. Maximum length L = n. But there are many windows of length n? Only one. But windows of length less than n also hold, but we only need max length. So b=1.
But could there be multiple windows of length n? Only the whole array.
So fine.
Now, double-check with some custom cases.
Case: n=5, k=2, h=[1,2,3,2,1]. Subarrays length 3? Let's compute max windows:
- [1,2,3] diff=2 <=2? 3-1=2 <=2 => valid. length=3.
- [2,3,2] diff=1 => valid.
- [3,2,1] diff=2 => valid.
- [1,2,3,2] diff=2? 3-1=2 => valid, length=4.
- [2,3,2,1] diff=2? 3-1=2 => valid, length=4.
- [1,2,3,2,1] diff=2? 3-1=2 => valid, length=5.
So maximum length =5, interval (1,5) only. So b=1.
Our sliding window will produce: at the end, max_len=5, interval (0,4) only.
Check: For r from 0 to 4, after each addition, we might get window length increasing. At r=4, after adjusting l will be 0, length=5 > previous max, clear and add. So fine.
Case: n=5, k=1, h=[1,2,1,2,1]. Maximum length? Let's examine:
- length 3: [1,2,1] diff=1? 2-1=1 valid; [2,1,2] diff=1; [1,2,1] again; [2,1,2] etc.
- length 4: [1,2,1,2] diff=1? max=2 min=1 diff=1 valid; [2,1,2,1] diff=1 valid.
- length5: [1,2,1,2,1] diff=1 valid. So max_len=5, interval only (1,5).
Our algorithm will capture.
Case: n=5, k=0, h=[1,1,2,1,1]. Maximum length? Subarray with all ones? Actually max-min<=0 means all elements equal. Longest contiguous segment of equal numbers. That could be length 2? At indices 1-2 (1,1) length2; also 4-5 (1,1) length2; maybe length 2. So max_len=2, and there are two intervals: (1,2) and (4,5). Our sliding window should capture both.
Simulate: n=5, h=[1,1,2,1,1], k=0.
Initialize l=0, max_len=0, res empty.
r=0: add 1, length=1 >0 -> max_len=1, res={(0,0)}
r=1: add index1 (1). Update deques. For max: back0 val=1 <=1? yes, pop0, push1 => maxdq [1]; min: back0 val=1 >=1? yes pop0, push1 => mindq [1]. Condition: max-min=0, length=2 >1? yes -> max_len=2, clear res, add (0,1).
Now l still 0? Actually after adding, condition holds, so no while. So length=2, update max_len=2, add (0,1). So res={(0,1)}.
r=2: add index2 (2). maxdq: back1 val=1 <=2? true pop1, push2 => [2]; mindq: back1 val=1 >=2? false, so push2 => [1,2] (since min increasing? Actually mindq currently [1] (1). For min, we want increasing, so we pop while back >= new element. 1>=2 false, so push2 -> [1,2] (values 1,2). Condition: max=2, min=1, diff=1 >0 -> need to shrink.
While loop:
check max front =2? l=0, not equal. min front=1? l=0 not equal? Actually min front=1 (index1). So l increments without popping? But we need to check if front == l. max front=2 !=0; min front=1 !=0. So we just l++? But we also must remove elements from deques that are out of window when l increments. In typical sliding window, when we increment l, we should check if front indices are < l, not just equal to old l. Because if we increase l by more than 1, front may become less than new l. So we need to ensure that deques only contain indices >= l. In our while loop, we increment l one by one, and at each increment we remove front if it equals the old l. But if we have a case where the front index is less than l after multiple increments? Actually we increment l one step at a time inside the while loop. At start, l=0. The while condition holds. We check if maxdq.front() == l (0) -> false; mindq.front() == l (0) -> false. Then we increment l to 1. But after increment, the front indices might now be < l? Let's see: maxdq front is index2 (value2) which is 2 >=1, okay. mindq front is index1 (value1) which is 1, now l=1, so index1 is not less than l; it's equal. But we didn't pop it because we only popped if front == old l (0). So after increment, it's still there, but mindq front index1 is exactly equal to new l? Actually new l=1, front=1, so it's okay. But if front was less than new l, that could happen if front was 0 and we incremented to 1 but didn't pop because we only compare to old l (0) and didn't pop because front != 0? But if front is 0, then front == old l (0) is true, so we would pop. So we are fine. But what about case where front is 2 and we increment l from 0 to 1? That's fine because 2>=1. So the algorithm seems okay: we increment l and pop only when the front index equals the l we are leaving (i.e., before increment). But is it possible that after incrementing, the front index is less than new l? That would imply front index < new l, which means front index was <= old l? Actually if we increment l by 1, new l = old l+1. For front index to be less than new l, it would need to be <= old l. Since we only remove front if it equals old l, if front index is less than old l, that shouldn't happen because we always maintain that all indices in deques are >= l. Initially after adding r, all indices in deques are between l and r. So front index >= l. If front index > l, then it will be >= l+1 = new l. So safe. So the method is correct.
Continue simulation:
After l becomes 1, condition? Now window is [1,2] (indices 1,2). max front = index2 (2), min front = index1 (1) diff=1 >0, still invalid. So while loop continues:
Now l=1: check max front (2) == l? 2==1 false; mindq front (1) == l? true, so pop mindq front (remove index1). mindq now [2] (value2). l++ => l=2.
Now window [2,2] (index2 only). Condition: max front=2, min front=2 diff=0 <=0. So exit while.
Length = 2-2+1=1. Since max_len=2, length< max_len, no addition.
Now r=3: add index3 (1). Update deques:
- maxdq currently [2] (value2). For max: while back <=1? 2<=1 false, push3 -> [2,3] (max order? Actually maxdq: we maintain decreasing. Currently front=2 (2), back=2. When we push 3 (1), back value 2 > 1, so we just push 3 -> [2,3]. This keeps decreasing because 2 > 1.
- mindq currently [2] (value2). For min: while back >=1? 2>=1 true, pop back (2). Now empty, push3 -> [3] (value1).
Now condition: max front=2 (value2), min front=3 (value1) diff=1 >0? Actually 2-1=1 >0, invalid. So while loop:
l=2: check max front (2) == l? yes, pop max front => maxdq becomes [3] (value1). Check mindq front (3) == l? 3==2 false. l++ => l=3.
Now window [3,3] only index3. Condition: max front=3 (1), min front=3 (1) diff=0 <=0. length=1.
No addition.
r=4: add index4 (1). Update deques:
- maxdq currently [3] (1). While back <=1? 1<=1 true, pop back (3), push4 -> [4] (1).
- mindq currently [3] (1). While back >=1? 1>=1 true, pop back (3), push4 -> [4] (1).
Condition: max-min=0 <=0, length = r-l+1 = 4-3+1 =2. Since length = max_len (2) we need to add (3,4) to res? But res currently contains (0,1). However we haven't updated max_len: it's still 2. So we should add (3,4) to res. So now res contains (0,1) and (3,4). But note: interval (3,4) corresponds to indices 4 and 5 (1-indexed) which are both 1's? Actually indices 4 and 5 are the last two ones. So that's correct: two intervals of length 2. But also there is interval (1,2) and (4,5). So that's good.
But we also have (0,1) which is indices 1-2 (1,1). And (3,4) indices 4-5 (1,1). However we also might have interval (2,3)? That is (2,3) indices 2 and 3 (1,2) diff=1 >0 so invalid. So only two intervals. So final res contains both. Output b=2. That matches expectation.
Thus algorithm works.
Now about memory: res could hold up to n intervals in worst case (if maximum length is 1, there are n intervals). n up to 1e5, storing n pairs is fine.
Now we need to implement in C++.
But wait: the problem states: "b — the amount of the time periods, during which Berlbury published a books". They say "a books" meaning exactly a books. So indeed intervals of length a. So we output all intervals of maximum length. That matches.
One nuance: Could there be intervals of length a that are not discovered because the sliding window's minimal l for a given r might not be exactly the start? As argued earlier, if a window [i, j] of length L (max) is valid, then for r=j, the minimal l that satisfies condition will be <= i. But could it be less than i? Suppose we have array: [1, 5, 1] with k=4. max length? Let's compute: L? All three? diff=4? 5-1=4 <=4? So L=3. Only one interval (1,3). For r=2 (index2?), Actually 0-index: [1,5,1], L=3. For r=2, what is the minimal l? The condition for window [0,2] holds because max=5 min=1 diff=4. So minimal l is 0. So length=3 = L. So we capture.
But suppose there is a scenario where a valid interval of length L exists, but for its right endpoint, there is also a longer valid window? That can't happen because L is maximum, so no longer exists. So minimal l for that r must equal the left of that interval.
Thus okay.
Now we also need to consider that we might have multiple maximum length intervals that end at same right? That's impossible because length fixed, left determined by right. So each right yields at most one.
Thus algorithm is correct.
Edge Cases: k negative? k is non-negative (0 ≤ k). So fine.
Now, complexity O(n). Use deques. Implementation:
-
Read n, k.
-
vector h(n);
-
for i = 0..n-1: cin >> h[i];
-
int l = 0, max_len = 0;
-
vector<pair<int, int>> ans;
-
deque max_dq, min_dq;
-
for (int r = 0; r < n; ++r) {
// add h[r] to deques
while (!max_dq.empty() && h[max_dq.back()] <= h[r]) max_dq.pop_back();
max_dq.push_back(r);
while (!min_dq.empty() && h[min_dq.back()] >= h[r]) min_dq.pop_back();
min_dq.push_back(r);
// shrink while condition violated
while (h[max_dq.front()] - h[min_dq.front()] > k) {
if (max_dq.front() == l) max_dq.pop_front();
if (min_dq.front() == l) min_dq.pop_front();
++l;
}
int cur_len = r - l + 1;
if (cur_len > max_len) {
max_len = cur_len;
ans.clear();
ans.push_back({l, r});
} else if (cur_len == max_len) {
ans.push_back({l, r});
}
}
-
Print max_len and ans.size()
-
For each pair in ans: print l+1 << " " << r+1 << endl.
But careful: ans is stored as we go. But there is a subtlety: When we update max_len to a larger value, we clear ans and add current interval. But what if later we find another interval of same length? We'll add. Good.
Now test on a tricky case: When there are multiple intervals of same max length, but we might add an interval that is not actually valid because after shrinking we got a window of length max_len, but could there be another left that yields same length? As argued, for given r, the minimal l is unique. If length = max_len, then it is valid. So fine.
But we must ensure that the condition h[max_dq.front()] - h[min_dq.front()] > k is correct. At each step after shrinking, the condition holds. However, we must also guarantee that the front elements are within the current window [l, r]. Since we remove from front only when they equal l, after incrementing l, if the front index is < l (should not happen) we might have a problem. But as argued, after incrementing l by one, we check again condition; if the front index becomes less than new l, then it must have been equal to old l, and we would have popped it. So safe.
But what about the case where we have duplicate values and deques might have multiple indices? Our removal only pops front if equals l. Suppose we have window where max value occurs at multiple positions. For example, array: [5,5] k=0. At r=1, we have maxdq [1] because we popped index0 when adding. So front=1. l=0 initially. Condition holds (max-min=0). No shrink. So ok.
Now consider scenario: window [l, r] valid but deques might have front indices that are not necessarily the min and max if we popped them incorrectly? Our deques maintain monotonic order: max_dq front is the index of the maximum value in the window; similarly min_dq front is index of minimum. This is standard.
Thus algorithm stands.
Now we also need to handle large n, but O(n) is fine.
Now, we should double-check that our condition for popping from deques while adding is correct: For max, we want to maintain decreasing order, so we pop from back while h[back] <= h[r]. For min, we maintain increasing order, so we pop from back while h[back] >= h[r]. That's typical.
Edge: The while condition for shrinking uses front indices. But after shrinking, we may have deques empty? Actually not empty because there is at least one element in the window (l <= r). So each deque will have at least one index. That's because we add r before the while loop, and the deques contain r at least. So they are non-empty.
Now, one more nuance: The while condition uses h[max_dq.front()] - h[min_dq.front()] > k. Since we maintain monotonic deques, this gives the current window's max and min. But could it be that the front of max_dq is not actually in the window because we haven't removed indices < l? We remove only when they equal l while shrinking. But what if we need to shrink more than 1? We increment l step by step and remove from front when index equals l. This ensures that after each increment, we remove any front that becomes out of window. But what about the case where the front index is less than l but not equal to l? That would only happen if we had skipped removing it earlier. But we always remove only when it equals the l we are about to increment. Could there be a situation where the front index is less than l after several increments because we didn't pop it? For that to happen, we must have had a front index that was < l at some point. But initially after adding r, we have deques with indices between current l and r. So all indices >= l. When we increment l by 1, we only pop if front equals old l. If front was greater than old l, it remains, and it's still >= new l because new l = old l+1 and front > old l => front >= old l+1 = new l. So it's still valid. So no issue.
Thus implementation is fine.
Now about answer format: first line: a (max length) and b (number of intervals). Then b lines each with start and end indexes. The problem statement uses "indexes of the first and the last volumes" which are 1-based.
Now, we should ensure we output b after we finish processing all r. So ans.size().
Now we need to consider if there is any corner case where max_len = 0? Since n >= 1, max_len at least 1.
Now test with a more complex case: Random.
But we should also think about potential performance: We are using deques and vector of pairs. That's fine.
Now finalize solution.
But wait: The problem might have many intervals: max_len could be small, e.g., 1, then there are n intervals. n up to 1e5, so outputting n lines is okay? The output size could be up to 1e5 lines, each with two numbers. That's about 2e5 numbers, which is fine. But we need to ensure not to store too many intervals? Storing n pairs of ints is okay (2*1e5 integers ~ 800KB). So fine.
But there's nuance: The problem statement: "In each of the following b lines print two integer numbers separated by a space — indexes of the first and the last volumes from each of the required time periods of Berlbury's creative work." Possibly they expect intervals in the order they appear? Usually they expect sorted order. Our algorithm adds them in increasing end index (and thus start index) order. So fine.
Now we must produce correct solution.
Now we need to write in C++.
But wait: There is a potential pitfall: In the shrinking loop, we use while (h[max_dq.front()] - h[min_dq.front()] > k). However, if after incrementing l we have deques empty? Not possible because at least r is present. But consider scenario: After popping from front because max_dq.front() == l, we might pop the only element. But then we also push r earlier, and r is still in deques? Actually if we pop the front that equals l, and l increments, it's possible that the popped element was also the only element in that deque? But then r is still there because we added it. So deques will not become empty. However, could it be that both deques pop their only element? That would require that both max and min indices are the same and equal to l, and we pop them, leaving the deques empty? But we have r added which is >= l+1 after increment? Let's examine: Suppose window is [l, r] and we have just added r. So deques contain at least r. Now if we shrink, we check condition; if it's violated, we increment l. Suppose r equals l? That can't happen because after adding, l <= r. If r = l, then window size 1, condition holds (diff=0) so we wouldn't be in while. So r > l. So there are at least two indices? Not necessarily; if r = l+1, then deques contain both indices? Could it be that both deques only contain r? For max, we popped back if <=, so if h[r] is larger than previous max, we might have popped older ones. If h[r] is smaller than previous max, max dq may still have the previous max index, which could be l. So max dq might have front = l, min dq might also have front = l? Actually min dq could have front = l as well. So both deques may have only l? But we also have r in deques? Let's see: For max dq, if h[l] > h[r], then max dq's back may be l, and when adding r, since h[r] <= h[l]? For max dq we pop while back <= h[r]. Since h[l] > h[r], we don't pop l. So max dq will have l at front? Actually the order is decreasing, so front is index of maximum. If h[l] is maximum, then max dq front is l (since it's the earliest index with that max?). But we maintain decreasing: front is the first element that is maximum; it could be l if l is the earliest index with that value. Meanwhile, r is added to back, but since h[r] is less, it stays. So max dq has at least two indices: l and r. But if h[l] is less than h[r], then when adding r, we pop all back elements <= h[r]; if l is at back? Actually l might be at back if it was the only element? But we need to think carefully.
Better to think: At time of adding r, we first push r onto deques, possibly popping some from back. So after this, both deques contain r (since we always push r). So there is at least r. So even if we later pop from front because front equals l, after popping, deques still contain r. So deques won't become empty. Good.
Thus condition is safe.
Now, check for large values: h up to 1e6, subtractions fit in int.
Now, we should also test with k=0, all elements distinct. Then max_len=1, intervals each