From 3ce2af21294197b277780857711dbee015f77ebc Mon Sep 17 00:00:00 2001 From: Prashant Goyal <48221944+prashant314@users.noreply.github.com> Date: Thu, 13 Oct 2022 21:34:22 +0530 Subject: [PATCH] Create SlidingWindow.md --- SlidingWindow.md | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 SlidingWindow.md diff --git a/SlidingWindow.md b/SlidingWindow.md new file mode 100644 index 0000000..7e6e764 --- /dev/null +++ b/SlidingWindow.md @@ -0,0 +1,33 @@ +#Sliding Window + +Time Space +Using Iteration : O(n*k) O(1) +Using AVL Trees/Priority Queue: O(n * logk) O(k) +Using Deque Amortized O(N) O(k) +since each element is processed (add/remove) at most twice. + +Eg. a = {4 , 1 , 3 , 5 , 1, 2 , 3 , 2 , 1 , 1 , 5 } , k=3 +Ans = {4, 5 , 5 , 5 , 3, 3, 3, 2, 5 } +Use a max heap, we insert the first 3 elements. And then return the top element 4. + + +``` +public int[] maxSlidingWindow(int[] nums, int k) { + PriorityQueue pq = new PriorityQueue<>(Collections.reverseOrder()); + int[] res = new int[nums.length-k+1]; + for(int i = 0; i