forked from LeetCode-in-Net/LeetCode-in-Net
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.cs
More file actions
38 lines (34 loc) · 1.13 KB
/
Solution.cs
File metadata and controls
38 lines (34 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
namespace LeetCodeNet.G0201_0300.S0239_sliding_window_maximum {
// #Hard #Top_100_Liked_Questions #Array #Heap_Priority_Queue #Sliding_Window #Queue
// #Monotonic_Queue #Udemy_Arrays #Big_O_Time_O(n*k)_Space_O(n+k)
// #2025_06_16_Time_32_ms_(94.92%)_Space_83.28_MB_(70.68%)
using System;
using System.Collections.Generic;
public class Solution {
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822", Justification = "LeetCode")]
public int[] MaxSlidingWindow(int[] nums, int k) {
int n = nums.Length;
int[] res = new int[n - k + 1];
int x = 0;
LinkedList<int> dq = new LinkedList<int>();
int i = 0;
int j = 0;
while (j < nums.Length) {
while (dq.Count != 0 && dq.Last!.Value < nums[j]) {
dq.RemoveLast();
}
dq.AddLast(nums[j]);
if (j - i + 1 == k) {
res[x] = dq.First!.Value;
++x;
if (dq.First.Value == nums[i]) {
dq.RemoveFirst();
}
++i;
}
++j;
}
return res;
}
}
}