
Sponsored
Sponsored
This approach involves checking each possible window (of length k) one by one and calculating the maximum for each window. This method is straightforward but inefficient for large arrays as it runs in O(n*k) time complexity.
Time complexity: O(n*k), where n is the number of elements.
Space complexity: O(1) for storing the maximum of each window in output array.
1#include <vector>
2#include <climits>
3#include <iostream>
4using namespace std;
5
6vector<int> maxSlidingWindow(vector<int>& nums, int k) {
7 vector<int> result;
8 for (int i = 0; i <= nums.size() - k; ++i) {
9 int max_val = INT_MIN;
10 for (int j = i; j < i + k; ++j) {
11 max_val = max(max_val, nums[j]);
12 }
13 result.push_back(max_val);
14 }
15 return result;
16}
17
18int main() {
19 vector<int> nums = {1, 3, -1, -3, 5, 3, 6, 7};
20 int k = 3;
21 vector<int> result = maxSlidingWindow(nums, k);
22 for (int num : result) {
23 cout << num << " ";
24 }
25 return 0;
26}In C++, a similar nested loop approach is utilized. The solution checks each window, finds the maximum, and stores it in a result vector.
Use a deque (double-ended queue) to store indices of array elements, which helps in maintaining the maximum for the sliding window in an efficient manner. As the window slides, the method checks and rearranges the deque so that the front always contains the index of the maximum element.
Time complexity: O(n), where n is the number of elements.
Space complexity: O(k) for the deque.
1
This JavaScript solution utilizes an array as a deque to maintain indices of relevant elements. The maximum element in a window is efficiently accessed using array operations to ensure correctness and performance.