I interviewed with Amazon a few days ago. I could not answer one of the questions the asked me to their satisfaction. I have tried to get the answer after the interview but I have not been successful so far. Here is the question:
You have an array of integers of size n. You are given parameter k
where k < n
. For each segment of consecutive elements of size k
in the array you need to calculate the maximum value. You only need to return the minimum value of these maximum values.
For instance given 1 2 3 1 1 2 1 1 1
and k = 3
the answer is 1
.
The segments would be 1 2 3
, 2 3 1
, 3 1 1
, 1 1 2
, 1 2 1
, 2 1 1
, 1 1 1
.
The maximum values in each segment are 3
, 3
, 3
, 2
, 2
, 2
, 1
.
The minimum of these values are 1
thus the answer is 1
.
The best answer I came up with is of complexity O(n log k). What I do is to create a binary search tree with the first k
elements, get the maximum value in the tree and save it in variable minOfMax
, then loop one element at a time with the remaining elements in the array, remove the first element in the previous segment from the binary search tree, insert the last element of the new segment in the tree, get the maximum element in the tree and compare it with minOfMax
leaving in minOfMax
the min value of the two.
The ideal answer needs to be of complexity O(n).
Thank you.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…