Algorithm Code
Time: O(n) | Space: O(1)
1function maxSlidingWindow(nums, k) {
2 let result = [];
3 let windowSum = 0;
4 for (let i = 0; i < nums.length; i++) {
5 windowSum += nums[i];
6 if (i >= k - 1) {
7 result.push(windowSum);
8 windowSum -= nums[i - k + 1];
9 }
10 }
11 return result;
12}Algorithm Steps
Step 1 of 14
1
Add nums[0] = 1 to window, sum = 1
2
Add nums[1] = 3 to window, sum = 4
3
Add nums[2] = -1 to window, sum = 3
4
Window full: push sum = 3, remove nums[0] = 1
5
Add nums[3] = -3 to window, sum = -1
6
Window full: push sum = -1, remove nums[1] = 3
7
Add nums[4] = 5 to window, sum = 1
8
Window full: push sum = 1, remove nums[2] = -1
9
Add nums[5] = 3 to window, sum = 5
10
Window full: push sum = 5, remove nums[3] = -3
11
Add nums[6] = 6 to window, sum = 14
12
Window full: push sum = 14, remove nums[4] = 5
13
Add nums[7] = 7 to window, sum = 16
14
Window full: push sum = 16, remove nums[5] = 3
1
3
-1
-3
5
3
6
7
Window sum: 1
Step 0 of 130%
0.25x4x