Intuition
For each window position, scan all k elements to find the maximum.
Explanation
Brute Force
For each window starting at index i (from 0 to n-k), scan the k elements nums[i..i+k-1] and record the maximum. This gives O(n*k) time since we have (n-k+1) windows each requiring O(k) work.
Space is O(n-k+1) for the output array, which is O(n).
Why it's slow: each window overlaps with the previous by k-1 elements, yet we re-examine all of them.
Implementation
class Solution {
public int[] maxSlidingWindow(int[] nums, int k) {
int n = nums.length;
int[] result = new int[n - k + 1];
for (int i = 0; i <= n - k; i++) {
int windowMax = nums[i];
for (int j = i; j < i + k; j++) {
windowMax = Math.max(windowMax, nums[j]);
}
result[i] = windowMax;
}
return result;
}
}