1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { const int n = nums.size(); vector<int> prefixMax(n), suffixMax(n); for (int i = 0; i < n; ++i) if (i % k == 0) prefixMax[i] = nums[i]; else prefixMax[i] = max(prefixMax[i - 1], nums[i]); suffixMax[n - 1] = nums[n - 1]; for (int i = n - 2; i >= 0; --i) if ((i + 1) % k == 0) suffixMax[i] = nums[i]; else suffixMax[i] = max(suffixMax[i + 1], nums[i]); vector<int> ans; for (int i = 0; i <= n - k; ++i) ans.push_back(max(suffixMax[i], prefixMax[i + k - 1])); return ans; } };
|