public int[] MaxSlidingWindow(int[] nums, int k) { if (nums == null || nums.Length == 0 || k <= 1) { return(nums); } int[] res = new int[nums.Length - (k - 1)]; int idx = 0; MonotonicQueue qu = new MonotonicQueue(); for (int i = 0; i < nums.Length; i++) { qu.Push(nums[i]); if (i - k + 1 >= 0) { res[idx++] = qu.Max(); if (nums[i - k + 1] == qu.Max()) { qu.Pop(); } } } return(res); }
public void GivenDecreasingSequence_MonotonicQueue_ShouldHaveFiveElements() { var input = new int[] { 5, 4, 3, 2, 1 }; var queue = new MonotonicQueue(); foreach (var item in input) { queue.Push(item); } Assert.IsTrue(queue.Peek() == 5); Assert.IsTrue(queue.Count == 5); }
public void GivenIncreasingSequence_MonotonicQueue_ShouldHaveOnlyOne() { var input = new int[] { 1, 2, 3, 4, 5 }; var queue = new MonotonicQueue(); foreach (var item in input) { queue.Push(item); } Assert.IsTrue(queue.Peek() == 5); Assert.IsTrue(queue.Count == 1); }
private List <int> FindMaximum(int[] array, int size) { var result = new List <int>(); var l = 0; var r = 0; var queue = new MonotonicQueue(); var currentWindowMaximum = int.MinValue; while (r < size) { if (array[r] > currentWindowMaximum) { currentWindowMaximum = array[r]; } queue.Push(array[r]); r++; } result.Add(currentWindowMaximum); while (r < array.Length) { if (array[l] == queue.Peek() && queue.Count > 1) { queue.Pop(); } queue.Push(array[r]); result.Add(queue.Peek()); l++; r++; } return(result); }