1. Brute Force — Re-Scan Each Window
Intuition
For every window [i, i + k - 1], compute the maximum element with a linear loop.
Algorithm
- Step 1: Loop
ifrom 0 toN - K. - Step 2: Find max in
nums[i ... i + K - 1]. - Step 3: Append max to result array.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution {public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { vector<int> result; int n = nums.size(); for (int i = 0; i <= n - k; ++i) { int maxVal = nums[i]; for (int j = i; j < i + k; ++j) { maxVal = max(maxVal, nums[j]); } result.push_back(maxVal); } return result; }}; int main() { Solution sol; vector<int> nums = {1, 3, -1, -3, 5, 3, 6, 7}; vector<int> res = sol.maxSlidingWindow(nums, 3); for (int x : res) cout << x << " "; cout << endl; // 3 3 5 5 6 7 return 0;}Time & Space Complexity
- Time complexity:
O(N * K)— Iterates over K elements for each of the (N - K + 1) windows. - Space complexity:
O(1) Auxiliary— Output array only.
Why Brute Force Doesn't Scale:
For N = 105 and K = 50,000, brute force takes 5 billion operations (> 10 seconds).
Monotonic deque processes N = 105 in 8 milliseconds.