Skip to content

Commit 3d08001

Browse files
Implement maximum sliding window algorithm
1 parent 2da0465 commit 3d08001

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

maximum sliding window

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)