Given an Array of Size n , that is it have n elements in it. and window size 'W'. you have to find maximum in all subarrays of size 'W'. starting from index 0.
Sample Input:
n=10 , W = 3 // n is number of element in array and W is window size.
10 3
1 -2 5 6 0 9 8 -1 2 0
Answer = 5 6 6 9 9 9 8 2
What i tried - (Self-Balancing BST)
- Pick first k elements and create a Self-Balancing Binary Search Tree (BST) of size W.
- Run a loop for i = 0 to n – W
- Get the maximum element from the BST, and print it.
- Search for arr[i] in the BST and delete it from the BST.
- Insert arr[i+W] into the BST.
Time Complexity:
- Step 1 is
O(WLogW).
- Time Complexity of steps 2.1, 2.2 and 2.3 is
O(LogW)
. Since Steps of 2.1, 2.2 and 2.3 are in a loop that runsn-W+1 times
, time complexity of the complete algorithm isO(WLogW + (n-W+1)*LogW)
which can also be written asO(nLogW)
.
My Question is can i improve it ? any suggestion on BST approach or Any other algorithm i haven't heard if ?
Everywhere i see only Dequeue Method. isn't there any Method ?