C# Solution O(n) Time O(K) space


  • 0
    U
    public class Solution {
        public int[] MaxSlidingWindow(int[] nums, int k) {
            if (nums == null || nums.Length < k || k == 0) return new int[0];
            int n = nums.Length; int[] ans = new int[n-k+1];
            int m = k+1;
            var dq = new int[m]; int start = 0; int end = 0;
    
            int index = 0;
            for(int i = 0; i < n; i++){
                if (i >= k && i-k == dq[start]) start = (start+1)%m;
                while (start != end && nums[i] >= nums[dq[(end+m-1)%m]]) end=(end+m-1) % m;
                dq[end] = i;
                end = (end+1)%m;
                if (i >= k-1) ans[index++] = nums[dq[start]];
            }
            return ans;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.