We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 2da0465 commit 3d08001Copy full SHA for 3d08001
maximum sliding window
@@ -0,0 +1,29 @@
1
+class Solution {
2
+ public int[] maxSlidingWindow(int[] nums, int k) {
3
+ int n = nums.length;
4
+ int[] result = new int[n - k + 1];
5
+ int maxIndex = -1;
6
+
7
+ for (int i = 0; i <= n - k; i++) {
8
+ // If maxIndex is outside current window, find new max
9
+ if (maxIndex < i) {
10
+ maxIndex = i;
11
+ for (int j = i; j < i + k; j++) {
12
+ if (nums[j] >= nums[maxIndex]) { // fix: include '=' for stability
13
+ maxIndex = j;
14
+ }
15
16
+ } else {
17
+ // Only compare the newly added element
18
+ int newElementIndex = i + k - 1;
19
+ if (nums[newElementIndex] >= nums[maxIndex]) { // fix: include '=' for stability
20
+ maxIndex = newElementIndex;
21
22
23
24
+ result[i] = nums[maxIndex];
25
26
27
+ return result;
28
29
+}
0 commit comments