Find all maximum sub-array in which all pairs have their sum >= k. I feel it can be solved using monotonic queue like this solution , but i am not able to think correct answer. Please give some hints.
e.g. Array :[ 1 5 2 3 6 5 4 2 2 8 ] and K = 8
then answer is [ 3 6 5 ] or [6 5 4 ] because any pair's sum is greater than or equal to 8
Yes, it can be solved using monotonic queue and two pointers.
Sub-array [l..r] is "good", if minimum(l..r) + second minimum(l..r) >= k, and that information can be stored in monotonic queue.
I tried . code but it does work for all cases . What am i doing wrong ?
1) You use stack with minimum, but you need queue with minimum. Queue implements on two stack :
2) You check minimum on segment + current > k, but it is not correct. You need check minimum on segment + next after minimum (second minimum) on segment > k.
For example,
Array :[ 1 5 2 3 6 5 4 2 2 8 ] and K = 8
Since queue in your solution is not monotonic ( increasing or decreasing ). How would you determine minimum and second minimum in O(1) ?
for e.g. at index 7 , queue = [3, 6, 5, 4] .
I use queue based on two stacks for minimum.
You can store at stack not only element, but triple(element, current minimum at stack, current second minimum at stack).
Queue for minimum is two stacks. When we add element in queue, we push triple in first stack. When we poll element, we pop triple from second stack; if second stack is empty, we push all triples from first stack in second in reverse order:
Minimum and second minimum in queue is minimum and second minimum of next 4 values:
For more information you can read this article (sorry, it is in Russian)
I am sorry, but why is [ 2 8 ] or [ 8 ] not included in the answer ?
Because it's not maximum subarray (their length is too small).