using System; using System.Collections.Generic; class Program { static void Main() { int[] nums = {1, 3, -1, -3, 5, 3, 6, 7}; int k = 3; var result = SlidingWindowMax(nums, k); Console.WriteLine(string.Join(", ", result)); } static int[] SlidingWindowMax(int[] nums, int k) { LinkedList<int> deque = new LinkedList<int>(); int[] res = new int[nums.Length - k + 1]; int ri = 0; for (int i = 0; i < nums.Length; i++) { while (deque.Count > 0 && deque.First.Value <= i - k) { deque.RemoveFirst(); } while (deque.Count > 0 && nums[deque.Last.Value] < nums[i]) { deque.RemoveLast(); } deque.AddLast(i); if (i >= k - 1) { res[ri++] = nums[deque.First.Value]; } } return res; } }
The code maintains a deque of indices where the values are in decreasing order. For each window, the front of the deque is the index of the maximum element. The output is the maximum for each sliding window of size 3.
Removing smaller elements from the back keeps the deque in decreasing order of values, so the front always holds the index of the maximum element in the current window.
int[] nums = {4, 2, 12, 3, 8}; int k = 3; LinkedList<int> deque = new LinkedList<int>(); int[] res = new int[nums.Length - k + 1]; int ri = 0; for (int i = 0; i <= nums.Length; i++) { while (deque.Count > 0 && deque.First.Value <= i - k) { deque.RemoveFirst(); } while (deque.Count > 0 && nums[deque.Last.Value] < nums[i]) { deque.RemoveLast(); } deque.AddLast(i); if (i >= k - 1) { res[ri++] = nums[deque.First.Value]; } }
The loop runs from i = 0 to i = nums.Length inclusive, but nums[nums.Length] is out of range causing IndexOutOfRangeException.
The deque stores indices only from the current window, so at most k indices can be stored.
using System; using System.Collections.Generic; class Program { static void Main() { int[] nums = {2, 2, -1, 3, 3, 0, 5, 5}; int k = 4; var result = SlidingWindowMax(nums, k); Console.WriteLine(string.Join(", ", result)); } static int[] SlidingWindowMax(int[] nums, int k) { LinkedList<int> deque = new LinkedList<int>(); int[] res = new int[nums.Length - k + 1]; int ri = 0; for (int i = 0; i < nums.Length; i++) { while (deque.Count > 0 && deque.First.Value <= i - k) { deque.RemoveFirst(); } while (deque.Count > 0 && nums[deque.Last.Value] < nums[i]) { deque.RemoveLast(); } deque.AddLast(i); if (i >= k - 1) { res[ri++] = nums[deque.First.Value]; } } return res; } }
The maximum values for each window of size 4 are 3, 3, 3, 5, and 5 respectively.
