5

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)

  1. Pick first k elements and create a Self-Balancing Binary Search Tree (BST) of size W.
  2. Run a loop for i = 0 to n – W
    1. Get the maximum element from the BST, and print it.
    2. Search for arr[i] in the BST and delete it from the BST.
    3. Insert arr[i+W] into the BST.

Time Complexity:

  1. Step 1 is O(WLogW).
  2. 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 runs n-W+1 times, time complexity of the complete algorithm is O(WLogW + (n-W+1)*LogW) which can also be written as O(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 ?

0 Answers0