Complete the code to declare a deque to store indices.
var deque = new [1]<int>();We use LinkedList<int> in C# to implement a deque because it allows adding and removing from both ends efficiently.
Complete the code to remove indices from the back while current element is greater.
while (deque.Count > 0 && nums[deque.Last.Value] [1] nums[i]) { deque.RemoveLast(); }
We remove indices from the back while the current element is greater than the element at those indices to maintain decreasing order.
Fix the error in removing indices out of the current window from the front.
if (deque.Count > 0 && deque.First.Value [1]= i - k + 1) { deque.RemoveFirst(); }
We remove from the front if the index is less than or equal to the start of the current window (i - k + 1).
Fill both blanks to add the current index and assign the max to result.
deque.[1](i); if (i >= k - 1) { result[i - k + 1] = nums[deque.[2].Value]; }
We add the current index to the back of the deque and take the front index's value as the max for the current window.
Fill all three blanks to complete the sliding window maximum function.
public int[] MaxSlidingWindow(int[] nums, int k)
{
if (nums == null || nums.Length == 0) return new int[0];
var result = new int[nums.Length - k + 1];
var deque = new LinkedList<int>();
for (int i = 0; i < nums.Length; i++)
{
while (deque.Count > 0 && nums[deque.Last.Value] [1] nums[i])
deque.RemoveLast();
deque.[2](i);
if (deque.First.Value [3] i - k)
deque.RemoveFirst();
if (i >= k - 1)
result[i - k + 1] = nums[deque.First.Value];
}
return result;
}The function removes smaller elements from the back (<), adds current index to the back (AddLast), and removes indices out of window from the front (<=).
