Advertisement
Guest User

Sliding Window Maximum

a guest
Feb 28th, 2022
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.98 KB | None | 0 0
  1. class Solution {
  2.     class MonotonicQueue {
  3.         Deque<Integer> queue;
  4.        
  5.         public MonotonicQueue() {
  6.              queue = new ArrayDeque<>();
  7.         }
  8.        
  9.         public void push(int a) {
  10.             while(!queue.isEmpty() && queue.peekLast() < a) {
  11.                 queue.pollLast();
  12.             }
  13.             queue.offerLast(a);
  14.         }
  15.  
  16.         public void pop(int a) {
  17.             if(a == queue.peekFirst()) queue.pollFirst();
  18.         }
  19.        
  20.         public int max() {
  21.             return queue.peekFirst();
  22.         }
  23.     }
  24.    
  25.     public int[] maxSlidingWindow(int[] nums, int k) {
  26.         int[] result = new int[nums.length - k + 1];
  27.  
  28.         MonotonicQueue mq = new MonotonicQueue();
  29.         for(int i = 0; i < nums.length; i++) {
  30.             mq.push(nums[i]);
  31.             if(i >= k - 1) {
  32.                 result[i - k + 1] = mq.max();
  33.                 mq.pop(nums[i-k+1]);
  34.             }
  35.         }
  36.         return result;
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement